Skip to content

Instantly share code, notes, and snippets.

@developit
Last active July 25, 2023 12:45
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save developit/ce414c36bb42e7f17d3e1fd099ac103c to your computer and use it in GitHub Desktop.
Save developit/ce414c36bb42e7f17d3e1fd099ac103c to your computer and use it in GitHub Desktop.
/**
* Usage:
* class FancyButton extends HTMLElement {
* constructor() {
* super();
* ensureShadowRoot(el);
* // if a declarative shadow root was present, it'll be here:
* console.log(this.shadowRoot);
* }
* }
*/
function ensureShadowRoot(el) {
let mode, t = el.firstElementChild;
if (mode = t && t.shadowRoot) {
t.remove();
el.attachShadow({mode}).append(...t.childNodes);
}
}
/**
* Alternative version that polyfills .attachShadow() with the DSD.
* Usage:
* class FancyButton extends HTMLElement {
* constructor() {
* super();
* // if a declarative shadow root was present, it'll be here:
* console.log(this.shadowRoot);
* }
* }
*/
var attach = HTMLElement.prototype.attachShadow;
Object.defineProperty(HTMLElement.prototype, 'attachShadow', {
value(opts) {
var t = this.firstElementChild;
var mode = t && t.localName==='template' && t.getAttribute('shadowroot');
var shadow = attach.call(this, opts);
if (mode) {
t.remove();
var c;
while (c = t.firstChild) shadow.appendChild(c);
}
return shadow;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment