Shadow roots used to exist only through attachShadow(), so a component had no shadow content until its JavaScript ran: server-rendered HTML couldn't contain it, and the first paint showed nothing or unstyled light DOM.
Declarative shadow DOM puts the shadow root in the markup:
<user-card>
<template shadowrootmode="open">
<style>h2 { margin: 0; }</style>
<h2><slot name="name"></slot></h2>
</template>
<span slot="name">Ada</span>
</user-card>
When the parser meets the <template shadowrootmode> start tag, it attaches a shadow root (open or closed) to the parent element and parses the template's content straight into it. No <template> remains in the DOM. Optional attributes map to attachShadow() options: shadowrootdelegatesfocus, shadowrootclonable, shadowrootserializable.
Why it matters for server rendering:
- The component's markup and scoped styles paint with the HTML, with no JavaScript, and stream in as they arrive.
- Hydration becomes attaching behaviour: when the definition loads, the upgraded element finds its root in
this.shadowRoot(or, for a closed root,this.attachInternals().shadowRoot) and adds listeners instead of re-rendering. - Serialization is symmetric:
element.getHTML({ serializableShadowRoots: true })emits<template shadowrootmode>for roots marked serializable, so a server-side DOM can produce it.
Where it applies. The document parser, Element.setHTMLUnsafe() and Document.parseHTMLUnsafe() attach declarative roots. innerHTML, insertAdjacentHTML() and DOMParser don't: the <template> stays an ordinary template. MDN's data lists shadowrootmode in Chrome 111, Firefox 123 and Safari 16.4.
Calling attachShadow() with the same mode on a host that has a declarative root returns that root, but empties it first.