Constructable Stylesheets

Constructable Stylesheets make it possible to create stylesheets imperatively by invoking the CSSStyleSheet() constructor. The CSSStyleSheet object has two new methods that make it safer to add and update stylesheet. These methods are replace and replaceSync. replace() returns a Promise that resolves once any external references (@imports) are loaded, whereas replaceSync() doesn’t allow external references at all.

Shadow DOM and Constructed StyleSheets

Constructable StyleSheets are very useful, when we use Shadow DOM. There is a new property called adoptedStyleSheets, which is available on Shadow Roots and Documents. This allows us to apply the styles defined by a CSSStyleSheet to a given DOM subtree. To do so, we set the property to an array of one or more stylesheets to apply to that element.


// Create our shared stylesheet:
const sheet = new CSSStyleSheet();
sheet.replaceSync('a { color: red; }');
// Apply the stylesheet to a document:
document.adoptedStyleSheets = [sheet];
// Apply the stylesheet to a Shadow Root:
const node = document.createElement('div');
const shadow = node.attachShadow({ mode: 'open' });
shadow.adoptedStyleSheets = [sheet];

With Constructable StyleSheets, web application developers now have an explicit solution for creating CSS StyleSheets and applying them to Shadow DOM trees.
The source code below, shows how to import a 'styles.css' file into the Grid's ShadowDOM.
const sheet = new CSSStyleSheet();
// replace all styles, allowing external resources:
sheet.replace('@import url("styles.css")')
  .then(sheet => {
	console.log('Styles loaded successfully');
  .catch(err => {
	console.error('Failed to load:', err);
grid.shadowRoot.adoptedStyleSheets = [sheet];

This entry was posted in Uncategorized and tagged , . Bookmark the permalink.

Leave a Reply