Re: [WICG/webcomponents] Copying global `<style>` textContent into ShadowDOM roots is not ideal. (#609)

In case anyone else searching for an answer comes across this thread, here is what I ended up doing, which works great:

```javascript
const copiedStyleSheet = new CSSStyleSheet();
document.addEventListener("DOMContentLoaded", () => {
    if (copiedStyleSheet.replace)
        copiedStyleSheet.replace(
            [...document.styleSheets].flatMap(
                sheet => [...sheet.cssRules].map(rule => rule.cssText)
            ).join(" ")
        );
    else
        for (const sheet of document.styleSheets)
            for (const rule of sheet.cssRules)
                copiedStyleSheet.insertRule(rule.cssText, copiedStyleSheet.cssRules.length);
});

class MyCustomElement extends HTMLElement {
    constructor() {
        super();
        this.attachShadow({ mode: "open" });
        this.shadowRoot.adoptedStyleSheets = [copiedStyleSheet];
    }
}
```

It's wasteful in that it constructs an independent stylesheet containing copies of all of `document`'s stylesheet rules, but at least all shadow roots can share the one `copiedStyleSheet` instance. It would be really fantastic if we could do `shadowRoot.adoptedStyleSheets = [...document.styleSheets]`, but alas, the spec inexplicably does not allow that.

-- 
Reply to this email directly or view it on GitHub:
https://github.com/WICG/webcomponents/issues/609#issuecomment-2063230563
You are receiving this because you are subscribed to this thread.

Message ID: <WICG/webcomponents/issues/609/2063230563@github.com>

Received on Thursday, 18 April 2024 07:43:07 UTC