Skip to content

EasyWebApp/declarative-shadow-dom-polyfill

Repository files navigation

Declarative Shadow DOM polyfill

Web standard polyfill for Declarative Shadow DOM

NPM Dependency CI & CD

NPM

Knowledge

  1. Proposal specification
  2. API documentation

Usage

Any one of these methods shown below is available.

1. CDN

<html>
  <head>
    <script src="https://polyfill.web-cell.dev/feature/DeclarativeShadowDOM.js"></script>

    <script src="./my-tag.js"></script>
    <script>
      window.onload = () => {
        const { shadowRoot } = document.querySelector("my-tag");

        console.log(shadowRoot);
      };
    </script>
  </head>
  <body>
    <my-tag>
      <template shadowrootmode="open">
        <p>Hello, Declarative Shadow DOM!</p>
      </template>
    </my-tag>
  </body>
</html>

2. Polyfill import

import "declarative-shadow-dom-polyfill";

const markup = `
<my-tag>
    <template shadowrootmode="open">
        <p>Hello, Declarative Shadow DOM!</p>
    </template>
</my-tag>`;

document.body.setHTMLUnsafe(markup);

console.log(document.body.getHTML());

const newDocument = Document.parseHTMLUnsafe(markup);

console.log(newDocument.body.getHTML());

3. Ponyfill import

import {
  getHTML,
  setHTMLUnsafe,
  parseHTMLUnsafe,
} from "declarative-shadow-dom-polyfill";

const markup = `
<my-tag>
    <template shadowrootmode="open">
        <p>Hello, Declarative Shadow DOM!</p>
    </template>
</my-tag>`;

setHTMLUnsafe.call(document.body, markup);

console.log(getHTML.call(document.body));

const newDocument = parseHTMLUnsafe(markup);

console.log(getHTML.call(newDocument.body));

4. Node.js & Bun

global.js

Either jsdom, happy-dom or linkedom is available DOM implementation.

import { JSDOM } from "jsdom";

const { window } = new JSDOM(),
  RequiredAPI = [
    "Text",
    "Comment",
    "CDATASection",
    "Element",
    "HTMLElement",
    "SVGElement",
    "ShadowRoot",
    "Document",
    "NodeFilter",
    "XMLSerializer",
    "DOMParser",
    "window",
    "document",
  ];

for (const key of RequiredAPI) Reflect.set(globalThis, key, window[key]);

index.js

import "./global";
import "declarative-shadow-dom-polyfill";

console.log(document.body.getHTML());