Last active
July 25, 2023 12:45
-
-
Save developit/ce414c36bb42e7f17d3e1fd099ac103c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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