Constructed Style Sheets
This is a new feature that allows you to create CSSStyleSheet objects. Their contents can be installed or imported from a CSS file using JavaScript and can be applied both to documents and to the shadow roots of web components. It will be available in Chrome version 73 and probably in the near future for Firefox.
There is a good article on the Google Developers site, but I will summarize it below with an example below.
Creating a style sheet
You create a new sheet by calling the constructor:
const sheet = new CSSStyleSheet();
Installation and replacement style:
You can apply style by calling the replace or replaceSync .
replaceSync is synchronous and cannot use any external resources: sheet.replaceSync('.redText { color: red }');
replace is asynchronous and can accept @import that reference external resources. Note that replace returns a Promise that should be handled accordingly. sheet.replace('@import url("myStyle.css")') .then(sheet => { console.log('Styles loaded successfully'); }) .catch(err => { console.error('Failed to load:', err); });
Applying style to a document or shadow DOM
You can apply the style by setting the adoptedStyleSheets attribute of either document or the shadow DOM.
document.adoptedStyleSheets = [sheet]
The array in adoptedStyleSheets frozen and cannot be modified using push() , but you can combine it by combining it with its existing value:
document.adoptedStyleSheets = [...document.adoptedStyleSheets, sheet];
Document Inheritance
The shadow DOM can inherit the created styles from the adoptedStyleSheets document in the same way:
// in the custom element class: this.shadowRoot.adoptedStyleSheets = [...document.adoptedStyleSheets, myCustomSheet];
Please note that if this is done in the constructor, the component will only inherit the stylesheets that were accepted before its creation. Setting adoptedStyleSheets to connectedCallback will be inherited for each instance when it is connected. It is noteworthy that this will not cause FOUC .
Web Components Example
Let's create a component called x-card that wraps the text in a beautiful div style.
<x-card>Example Text</x-card> <x-card>More Text</x-card>
source share