shadowRoot.attachStyleSheets() in custom elements

To use web components with slots you have to use a shadowRoot, but you don't always want a full isolate of the styles.

In the case that you want to use the global styles you have to make adjustments like the following:

const sheet = new CSSStyleSheet();

// Add global CSS to apply to the shadowRoot
for (let { cssRules } of document.styleSheets) {
  for (let rule of cssRules) sheet.insertRule(rule.cssText);  
}

shadowRoot.adoptedStyleSheets = [sheet];

However, it is not a complete solution, since it will not react to runtime changes in global styles.

In the end you have to make things easier for developers without breaking the current shadowRoot to not break anything, so a new method to make this connection with the changes made in document.styleSheets would be the best.

So:

shadowRoot.attachStyleSheets();

It would solve many current problems that people have with web components.

This discourse is for the JavaScript language - which doesn't have CSS or the DOM. You may want to try https://github.com/whatwg or Stack Overflow.

2 Likes