Is there a polyfill for Declarative Shadow DOM?

posted on

Back to overview

Yes, kinda.

Building a polyfill for declarative shadow DOM is straightforward: you find all <template shadowrootmode> elements and convert them to attached Shadow Roots on their parent element.
That allows the web component to function in unsupported browsers but only when JavaScript is enabled and functioning.

(function attachShadowRoots(root) {
  // find all templates with a shadowrootmode attribute
  root.querySelectorAll("template[shadowrootmode]").forEach(template => {
    // get the mode: open or closed
    const mode = template.getAttribute("shadowrootmode");
    // attach a shadow to the component
    const shadowRoot = template.parentNode.attachShadow({ mode });
    // append the content in the template
    // remove the template

You should see a 4px dotted blue border, even in Firefox.

Source: Declarative Shadow DOM

Back to overview