What is the Shadow DOM?

Posted by on Jun 22, 2015 in JavaScript, WebDev

Shadow What?

I’ve seen lots of queries on SO and various programming forums regarding the Shadow DOM. It seems lots of developers know that it exists, but many of those do not understand its purpose or significance. Moving forward, Shadow DOM is going to play a significant role in web development, not least as a core part of the web components specification.

So What is it?

At its highest level, the Shadow DOM is an emerging standard that allows you to encapsulate content (not just HTML) from the main document. This means you can ‘embed’ styles and markup completely decoupled from the rest of the web page and not have to worry about naming collisions, JavaScript conflicts or other quirks commonly found on large pages that use multiple frameworks from sources.

So what is the problem?

Imagine, if you will, a fancy all-singing, all-dancing video player. This reusable component if made available on the web for inclusion on your page (or even the native HTML5 video player supplied by the browser vendor). There are few scenarios where you would want other styles on the page to affect the core elements of the player (e.g. play/pause button) and you don’t want to have to worry about elements on your page conflicting with that of the video player.
This is a very real worry but this is exactly the kind of problem the Shadow DOM is intended to solve.

How does it work?

At a simple level, with Shadow DOM any element can have a new node called the shadow root. This is the isolation boundary assigned to that individual element. The hosting element becomes the shadow host. This isolation provides great protection but also allows you to access the parent document via JavaScript so other parts of the page remain accessible (e.g. form controls)

Can I start to use it?

At the time of writing, we’re some way from full browser support. There are polyfills available (e.g. platform.js (https://www.polymer-project.org/0.5/docs/start/platform.html)) but as always, check the status on CanIUse.com for up-to-date information