CodeBlanks Logo Icon CodeBlanks

Declarative shadow DOM

HTML course · Advanced · Lesson 39/56

Write declarative shadow DOM with <template shadowrootmode>.

What is declarative shadow DOM?

Classic shadow DOM needs JavaScript: you call attachShadow and wire the template by hand. Declarative shadow DOM does the same job with HTML alone; no JavaScript wait.

You write <template shadowrootmode="open">. The browser sees the template and attaches the shadow root at once. When the page first paints, the component is ready; no flash, no jump.

Writing template shadowrootmode

For declarative shadow DOM you write <template shadowrootmode="open">. Inside that template goes the normal shadow skeleton: <style>, <div>, <slot>.

The moment the browser sees the template, it attaches a shadow root and moves the template's content into it. So the component looks right even before JavaScript loads. This is especially valuable for projects that render HTML on the server.

Server-side rendering

The biggest win for declarative shadow DOM is in server-rendered HTML. The server ships the component's shadow structure straight as HTML; the browser paints the right result without waiting for JavaScript.

This speeds up the first paint and reduces flicker. Even with JavaScript disabled, the component still looks right. Modern frameworks prefer this method for server-side rendering.

Exercise Write a declarative shadow DOM skeleton

Add a <template shadowrootmode="open"> to body. Inside it put a <style> (content: p { color: blue; }) and a <slot>.

Show example solution
<body>
  <template shadowrootmode="open">
    <style>p { color: blue; }</style>
    <slot></slot>
  </template>
</body>

Test yourself

  1. What value does the shadowrootmode attribute take?

    • open or closed
    • visible
    • hidden
    • true or false
    Show answer

    open or closed — Correct. shadowrootmode takes 'open' or 'closed'.

  2. Write the shadowrootmode attribute

    <template ____>
      <slot></slot>
    </template>
    Show answer
    <template shadowrootmode="open">
      <slot></slot>
    </template>
  3. Match declarative shadow DOM terms

    shadowrootmode
    shadow root mode
    open
    allows outside access
    closed
    blocks outside access
    declarative
    no JavaScript

All lessons in Advanced