Angular 101 – What is the “shadow” DOM?

If you have spent any time with a javascript library you are bound to have heard of the “shadow dom”. This shadowy superhero wanders around Gotham righting wrongs and fighting injustice.  OK, so that’s just what I thought when I first heard the term.

Wikipedia describes the shadow DOM as:

Shadow DOM is a functionality that allows the web browser to render DOM elements without putting them into the main document DOM tree. This creates a barrier between what the developer and the browser can reach; the developer cannot access the Shadow DOM in the same way they would with nested elements, while the browser can render and modify that code the same way it would with nested elements.

So that doesn’t help! Let’s start with the problem. What happens when two libraries try to manipulate the dom. In fact, let’s go back to basics. What is the DOM (Document Object Model)? The DOM is just the browsers representation of a web page. HTML is the initial state, used to generate the initial DOM. Once it’s loaded, the DOM is manipulated by scripts and events.

Problems can occur when two libraries try to manipulate the same part of the DOM. Maybe they’ve both used the same name for different things. This problem is solved by encapsulation.

Shadow DOM solves this problem by letting libraries define their own mini DOM (or shadow dom) and attach it to the main dom. Preventing it from clashing with anything else.

Angular makes heavy use of the shadow dom. It’s one of the defining features of Angular 2+.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.