Shadow DOM plays an important role in the world of web components as they provide an easy way to encapsulate, but they were created imperatively using JavaScript, with something like:
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 applications, but has lots of challenges to express and build them on the server (SSR). That’s when declarative shadow comes into picture!
Declarative Shadow DOM (DSD)
Declarative Shadow DOM helps us to have Shadow DOM on the server with ease. The sample imperative example above would look like:
<fancy-element>
<template shadowroot="open">
<slot></slot>
</template>
<h2>Declarative Shadow DOM</h2>
</fancy-element>
P.S: chrome://flags/#enable-experimental-web-platform-features should be enabled as of today to use this feature.
About Hemanth HM
Hemanth HM is a Sr. Machine Learning Manager at PayPal, Google Developer Expert, TC39 delegate, FOSS advocate, and community leader with a passion for programming, AI, and open-source contributions.