Gopherkhan Gopherkhan - 5 months ago 23
Javascript Question

ShadowDOM vs Document Fragments -- How do they differ?

Looking into articles on ShadowDOM it seems like it's an enhancement to DocumentFragments. What is the real benefit of ShadowDOM? CSS specificity? Can't I do roughly the same things with Fragments?

I'm looking for a list of capabilities for each. For example, both seem to allow you to assemble a dom tree in memory and off the main render path. However, ShadowDOM seems to have the added benefit of scoped CSS.

What are cases where you would use ShadowDOM vs where you would just want to use DocumentFragments?


After looking into this more myself, I see the two technologies are completely orthogonal.

Note: Since the question has been closed, I cannot answer it myself. I originally put details of my findings into a comment below, but figured more people will check the text up here.

Document Fragments are a Javascript/DOM construction tool, used for creating a non-heirarchical collections of nodes (each of which could be the parent of other nodes) off the DOM. They are essentially a wrapper around the node-collection, which gets abandoned once the fragment is appended to the DOM. DocumentFragments allow you to collect a number of nodes at the same level, and append them to another DOM node as siblings.

Shadow Dom is all about isolation of side-effects within a larger rendered DOM. ShadowDom allows you to create sandboxed reusable components with encapsulated styles. When a ShadowDom-based component is added to a larger web application, its CSS styles will not leak out into the rest of the application, nor will the application's own styles affect the rendering of the component.

Note that CSS combinators such as

exist for styling (and selecting) shadowDom components from the parent dom, but these are being deprecated in the near future. Because of this, it is recommended reusable Components utilizing ShadowDOM rely on CSS Variables for styling, if they intend to be customized by the application that consumes them.


From what I've read and the way I use it, is ShadowDom has to do with encapsulation like if you put a <style> tag inside the ShadowDom the css will only be applied to the ShadowDom and document fragments has to do with browser reflow