Skip to content

This notebook belongs to

Sadat Jubayer

Senior Software Engineer at Premio

If found, please return to hello@jubayer.dev

Vol. 7Seven years of building

Started
January 2020
Everyday tools
TypeScript, Vue, React, Next.js, NestJS, React Native
Education
B.Sc. CSSE, AIUB, 2020
1 min readWeb Platform

Render components with declarative shadow DOM

Ship a shadow root in the initial HTML so a web component can render its styled content before its JavaScript loads.

A status badge can show its styled content before its custom element script loads. Send the shadow tree with the page HTML and let the browser parser attach it to the host.

Put the template inside the host

Return this HTML as the page response. The shadowrootmode="open" attribute goes on a template whose parent is the custom element.

<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>Service status</title>
<status-badge>
  <template shadowrootmode="open">
    <style>
      .badge {
        display: inline-block;
        border: 1px solid currentColor;
        border-radius: 1rem;
        padding: 0.2rem 0.6rem;
      }
    </style>
    <span class="badge"><slot></slot></span>
  </template>
  Online
</status-badge>
</html>

Load the page with scripts disabled and you see Online inside a rounded border. The parser attaches the shadow root to status-badge and puts the style and span inside it.

diagram

From template to shadow tree

The parser builds a shadow root from the template while Online stays a light DOM child.

The word Online remains outside the root as light DOM text. The slot is where the browser displays that text. Inspect the host in DevTools and expand #shadow-root (open) to see the span. The template itself is gone from the resulting tree.

Reuse the root when the script arrives

If you define status-badge in a script, start from the existing this.shadowRoot when it is present. Attach and populate a root in the branch where there is none. Then wire behaviour to the matching nodes in either case.

Calling attachShadow with the same mode returns the declarative root and clears its children. That can erase the badge during upgrade. Check for the root before the call so the script uses the markup you already shipped.

Check how the markup got into the page

If DevTools still shows an inert template and no shadow root, check how you inserted the HTML. The document parser handles the template in the initial response, but setting an element’s innerHTML to the same markup does not attach a root. Test this example as a document response to see what the browser can show before your component code runs.