Skip to content

Instantly share code, notes, and snippets.

@mayank99
Created June 26, 2025 22:39
Show Gist options
  • Save mayank99/5a0f00747c42bd15aa386b95cd9edaef to your computer and use it in GitHub Desktop.
Save mayank99/5a0f00747c42bd15aa386b95cd9edaef to your computer and use it in GitHub Desktop.
async function createShadowRoot(
element: HTMLElement,
options: {
html: string;
css?: string;
js?: (element: HTMLElement) => void | Promise<void>;
},
) {
const _window = element.ownerDocument.defaultView || window;
const { html, css, js } = options;
const shadowRoot = element.attachShadow({ mode: 'open' });
shadowRoot.innerHTML = html;
const styleSheet = new _window.CSSStyleSheet();
shadowRoot.adoptedStyleSheets.push(styleSheet);
const promises = [
css ? styleSheet.replace(css) : undefined,
js ? js(element) : undefined,
];
await Promise.all(promises.filter(Boolean));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment