Hemanth.HM

A Computer Polyglot, CLI + WEB ♥'r.

Declarative Shadow DOM

| Comments

Shadow DOM plays an important role in wold of web components as they provide an easy way to encapsulate, buu they were created imperatively using JavaScript, with something like:

1
2
3
4
5
6
7
8
9
10
class FancyElement extends HTMLElement {
    constructor() {
        super();
        this.ShadowRoot = this.attachShadow({ mode: "open" });
        this.ShadowRoot.innerHTML = "Shadow DOM imperative";
    }
}

customElements.get("imperative-fancy-element") ||
    customElements.define("imperative-fancy-element", FancyElement);

Well, this works fine for client-side only application, but has lot of challenges to express and build them on the server (SSR), that when declarative shadow comes into picture!

Declarative Shadow DOM (DSD) helps us to have Shadow DOM to the server with ease, the sample imperative example as above would look like:

1
2
3
4
5
6
<fancy-element>
    <template shadowroot="open">
        <slot></slot>
    </template>
    <h2>Declarative Shadow DOM</h2>
</fancy-element>

Here is codesandbox:

P.S: chrome://flags/#enable-experimental-web-platform-features should be enabled as of today to use this feature.

Comments