Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 39 ยท Shadow DOM

Declarative Shadow DOM

Create shadow roots straight from HTML with template shadowrootmode, render components on the server, hydrate them, and use getHTML and setHTMLUnsafe from script.

Everything so far created shadow roots with JavaScript: attachShadow inside a constructor. That has a cost. The page must download and run script before the component shows anything, and server-rendered HTML cannot contain a component's internal markup. Declarative Shadow DOM (DSD) fixes this by letting HTML itself describe a shadow root.

The syntax

You put a <template> with a shadowrootmode attribute as the first child of the host. When the HTML parser reaches it, it creates the shadow root, moves the template's content into it and removes the template element.

HTML
<user-badge>
  <template shadowrootmode="open">
    <style> span { color: teal; } </style>
    <span>Rendered without JavaScript</span>
  </template>
</user-badge>

The value is open or closed (like mode). Because the shadow tree exists as soon as the HTML is parsed, the browser can paint it before any script loads.

A shadow root written in HTML

No class and no customElements.define exist here, yet the shadow tree renders with its own styles. This works even for plain elements like <div>. The <template> is consumed by the parser: the last line prints false.

Attaching behavior later

DSD is only HTML. To add behavior, define the custom element afterward. When the class upgrades the host, its constructor calls attachShadow, which would normally throw because a shadow root exists. Use ElementInternals.shadowRoot, which returns the existing root (even a closed one) to the component:

JavaScript
class UserBadge extends HTMLElement {
  #internals = this.attachInternals();

  constructor() {
    super();
    // Use the declarative root if the parser made one, otherwise create it.
    this.root = this.#internals.shadowRoot ?? this.attachShadow({ mode: "open" });
  }

  connectedCallback() {
    if (!this.root.querySelector("span")) {
      this.root.innerHTML = "<span>Client-rendered fallback</span>";
    }
    this.root.querySelector("span").addEventListener("click", () => {
      console.log("hydrated: click works");
    });
  }
}
customElements.define("user-badge", UserBadge);

This pattern is the core of hydration: server-rendered markup arrives first, and the class attaches event listeners later.

Hydrating a declarative root

For the first 800 ms the button is visible but inert; then the class upgrades the element and reuses the existing shadow root. A server-rendered component would behave the same, painting early and becoming interactive later.

Where DSD is useful

  • Server-side rendering of design-system components with no client JavaScript for the first paint.
  • Static sites that want style encapsulation without a script.
  • Avoiding layout shift: the content is there from the first byte.
  • Streaming HTML: shadow roots can arrive in chunks.

The downsides: markup is repeated for each instance (styles inside each template), so keep component styles small or link to a shared external stylesheet. Server frameworks that support DSD generate the template for you.

Creating DSD from script

innerHTML does not run the DSD logic: for security reasons the template remains an inert <template>. The newer APIs setHTMLUnsafe and parseHTMLUnsafe do parse declarative shadow roots:

setHTMLUnsafe and getHTML

innerHTML leaves the template inert (false), while setHTMLUnsafe creates the root (true) in current browsers. The name warns you that no sanitization is performed, so use it only with trusted markup. To include a shadow root in the output of getHTML, the root must be created with serializable: true; roots made by DSD parsing are serializable only if the template has the shadowrootserializable attribute.

Extra template attributes

Attribute Equivalent option
shadowrootmode="open|closed" mode
shadowrootdelegatesfocus delegatesFocus: true
shadowrootclonable clonable: true
shadowrootserializable serializable: true

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which markup creates a declarative shadow root?

    The HTML parser turns a template with shadowrootmode into a shadow root for its parent element.
  2. 2. Does element.innerHTML = '<div><template shadowrootmode=open>...' create the shadow root?

    innerHTML deliberately ignores declarative shadow roots; the unsafe parsing APIs honor them.
  3. 3. How can a custom element class reuse a shadow root that the parser already made?

    ElementInternals.shadowRoot returns the existing root, even if it is closed.
  4. 4. What is the main benefit of declarative shadow DOM?

    The shadow tree exists from parsing, so HTML from a server shows complete components before any script runs.

Summary

  • <template shadowrootmode="open"> as the first child of a host creates a shadow root while parsing.
  • The class can later reuse the root through attachInternals().shadowRoot to hydrate it.
  • innerHTML ignores DSD; setHTMLUnsafe and parseHTMLUnsafe honor it.
  • DSD enables server rendering, no-script encapsulation and layout stability.
  • Extra attributes mirror the attachShadow options.

Next: The template Element