Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 39 ยท Tooling and Patterns

Declarative Shadow DOM and Server Rendering

Render shadow DOM straight from HTML with the shadowrootmode attribute so components appear without JavaScript, then hydrate them. Includes server-side output patterns.

Until recently a shadow root could only be created by JavaScript with attachShadow(). That meant a server could not send a fully styled component: the user saw nothing (or unstyled light DOM) until scripts downloaded and ran. Declarative Shadow DOM (DSD) fixes this. You describe the shadow root in HTML with a <template shadowrootmode="open">, and the HTML parser builds the shadow tree itself, with no JavaScript.

That unlocks server-side rendering (SSR) and static generation for web components, and faster first paint.

The syntax

Put a <template> with the attribute shadowrootmode as a direct child of the host:

HTML
<x-greeting>
  <template shadowrootmode="open">
    <style>p { color: teal; }</style>
    <p>Hello from a shadow root, <slot></slot>!</p>
  </template>
  Ada
</x-greeting>

When the parser meets the template, it attaches a shadow root to its parent (the host), moves the template's content into it, and removes the template element. The text Ada stays in the light DOM and is slotted. No script ran.

Options map onto attachShadow arguments: shadowrootmode="open" or "closed", plus shadowrootdelegatesfocus, shadowrootclonable and shadowrootserializable attributes.

A shadow root created by the HTML parser

No customElements.define was called, yet the host already has a styled shadow tree: the paragraph inside is teal while the page paragraph is crimson. This is the whole idea: the browser renders the encapsulated UI straight from markup.

Declarative Shadow DOM is part of the HTML parser, so it works in markup parsed with the page or setHTMLUnsafe() / parseHTMLUnsafe(). It does not work when you assign innerHTML, for security reasons. Use el.setHTMLUnsafe(html) (when available) or the DOMParser option for that case.

Hydration: attaching behavior later

The server output has structure and style but no behavior. When the component class is defined later, the element upgrades. In the constructor, the shadow root already exists, so you must reuse it instead of calling attachShadow() again (that would throw). ElementInternals offers a way to fetch it, even for closed roots:

JavaScript
constructor() {
  super();
  const internals = this.attachInternals();
  this.root = internals.shadowRoot ?? this.attachShadow({ mode: "open" });
}

Then wire up events and read state from the existing DOM instead of rebuilding it.

Hydrating server-rendered markup

Click Like first: nothing happens. Press Define x-like and click again: the count increments. The component kept the server's markup (the initial 3) and added behavior only.

Server rendering patterns

A server (PHP, Node, Python, any templating language) only needs to print the template. The skeleton is:

PHP
<?php $name = htmlspecialchars($user['name']); ?>
<x-greeting>
  <template shadowrootmode="open">
    <style><?= $componentCss ?></style>
    <p>Hello, <slot></slot>!</p>
  </template>
  <?= $name ?>
</x-greeting>

Things to plan for:

  • Escape all dynamic data as you would in any HTML. DSD does not sanitize.
  • Repeated CSS: each instance carries its own <style>, which bloats pages with many instances. Alternatives are a shared stylesheet linked inside the template (<link rel="stylesheet" href="...">, cached by the browser) or, after upgrade, switching to adoptedStyleSheets as in the host selectors lesson.
  • Match client and server output so hydration does not cause flashes.
  • Frameworks: Lit offers a server renderer package, Stencil and Enhance can output DSD, and Astro and 11ty plugins exist. These tools are read-only here, as no build step runs on the site.

Support and fallbacks

Declarative Shadow DOM with the shadowrootmode attribute is supported by current Chrome, Edge, Safari and Firefox. Older browsers that do not understand it leave the <template> inert in the DOM, so the shadow content simply does not render. For a safety net, you can detect it (HTMLTemplateElement.prototype.hasOwnProperty("shadowRootMode")) and, when missing, promote templates with a short script:

JavaScript
if (!HTMLTemplateElement.prototype.hasOwnProperty("shadowRootMode")) {
  document.querySelectorAll("template[shadowrootmode]").forEach((t) => {
    const root = t.parentElement.attachShadow({ mode: t.getAttribute("shadowrootmode") });
    root.append(t.content);
    t.remove();
  });
}

Place it after the markup (or run it on DOMContentLoaded) so the templates exist.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which attribute turns a template into a declarative shadow root?

    The HTML parser recognises <template shadowrootmode> as a request to attach a shadow root to the parent.
  2. 2. What must the constructor do when the shadow root may already exist?

    Calling attachShadow on an element that already has a shadow root throws, so check internals.shadowRoot first.
  3. 3. Why does assigning el.innerHTML not create declarative shadow roots?

    innerHTML ignores shadowrootmode; other parser-based APIs such as setHTMLUnsafe can create them.
  4. 4. What is the main benefit of Declarative Shadow DOM?

    The parser builds the shadow tree, so server-rendered components display immediately and hydrate later.

Summary

  • <template shadowrootmode="open"> inside a host makes the parser create a shadow root.
  • It enables SSR and static output of encapsulated, styled components with no JavaScript.
  • On upgrade, reuse the existing root through internals.shadowRoot and attach behavior.
  • Escape dynamic data, manage repeated CSS, and keep a small fallback for older browsers.

Next: Project: Toast Notifications