可建構的樣式表

可重複使用的風格、

可建構的樣式表是使用陰影 DOM 建立及發布可重複使用的樣式。

瀏覽器支援

  • 73
  • 79
  • 101
  • 16.4

資料來源

您隨時可以使用 JavaScript 建立樣式表。不過,該程序向來都是使用 document.createElement('style') 建立 <style> 元素,然後存取其工作表屬性,取得基礎 CSSStyleSheet 執行個體的參照。這個方法可能會產生重複的 CSS 程式碼和其總體,而附加的行為會導致未設定樣式的內容閃爍 (無論內容是否過大)。CSSStyleSheet 介面是一組 CSS 表示法介面的根層級 (稱為 CSSOM),提供程式輔助方式操控樣式表,並消除與舊方法相關的問題。

顯示 CSS 準備與應用的圖表。

您可使用可建構的樣式表,定義及準備共用 CSS 樣式,然後將這些樣式輕鬆套用至多個「陰影根」或文件,不必重複。對共用 CSSStyleSheet 的更新會套用至所有已採用該架構的根層級,且在工作表載入後,採用樣式表的速度就會快速且同步。

透過 buildable Stylesheet 設定的連結,已適合許多不同的應用程式。這可以用於提供由多個元件使用的集中式主題:主題可以傳遞給元件的 CSSStyleSheet 執行個體,而主題更新會自動套用到元件。可用來將 CSS 自訂屬性值發布到特定的 DOM 子樹狀結構,而不需依賴階層。甚至可做為瀏覽器 CSS 剖析器的直接介面使用,這樣您就不必將樣式表插入 DOM,藉此輕鬆預先載入樣式表。

建立樣式表

與其導入新的 API 來達成這個目的,只要使用建構函式規格,即可叫用 CSSStyleSheet() 建構函式以建立樣式表。產生的 CSSStyleSheet 物件有兩個新方法,可在不觸發未設定樣式的 Flash (FOUC) 的情況下,更安全地新增及更新樣式表規則。replace()replaceSync() 方法都會以 CSS 字串取代樣式表,而 replace() 會傳回 Promise。這兩種情況下都不支援外部樣式表參照,系統會忽略所有 @import 規則並產生警告。

const sheet = new CSSStyleSheet();

// replace all styles synchronously:
sheet.replaceSync('a { color: red; }');

// replace all styles:
sheet.replace('a { color: blue; }')
  .then(() => {
    console.log('Styles replaced');
  })
  .catch(err => {
    console.error('Failed to replace styles:', err);
  });

// Any @import rules are ignored.
// Both of these still apply the a{} style:
sheet.replaceSync('@import url("styles.css"); a { color: red; }');
sheet.replace('@import url("styles.css"); a { color: red; }');
// Console warning: "@import rules are not allowed here..."

使用建構的樣式表

Buildable StyleSheets 的第二個新功能是 adoptedStyleSheets 屬性,適用於Shadow Roots文件。這樣就能將 CSSStyleSheet 定義的樣式明確套用至指定的 DOM 子樹狀結構。為此,我們會將屬性設為一或多個樣式表的陣列,並套用至該元素。

// Create our shared stylesheet:
const sheet = new CSSStyleSheet();
sheet.replaceSync('a { color: red; }');

// Apply the stylesheet to a document:
document.adoptedStyleSheets.push(sheet);

// Apply the stylesheet to a Shadow Root:
const node = document.createElement('div');
const shadow = node.attachShadow({ mode: 'open' });
shadow.adoptedStyleSheets.push(sheet);

Putting it all together

With Constructable StyleSheets, web developers now have an explicit solution for creating CSS StyleSheets and applying them to DOM trees. We have a new Promise-based API for loading StyleSheets from a string of CSS source that uses the browser's built-in parser and loading semantics. Finally, we have a mechanism for applying stylesheet updates to all usages of a StyleSheet, simplifying things like theme changes and color preferences.

View Demo

Looking ahead

The initial version of Constructable Stylesheets shipped with the API described here, but there's work underway to make things easier to use. There's a proposal to extend the adoptedStyleSheets FrozenArray with dedicated methods for inserting and removing stylesheets, which would obviate the need for array cloning and avoid potential duplicate stylesheet references.

More information