[英]Load essential styles to shadow-dom
我喜歡 shadow dom 樣式封裝的想法,但我想為每個 shadow dom(重置、排版等)包含基本樣式。
<head>
<link rel="stylesheet" href="core.css">
...
</head>
<my-component></my-component>
<script>
customElements.define('my-component', class MyComponent extends HTMLElement {
...
connectedCallback() {
this.shadow = this.attachShadow({mode: 'open'});
const linkElem = document.createElement('link');
linkElem.setAttribute('rel', 'stylesheet');
linkElem.setAttribute('href', 'core.css');
// applying exiting "core.css" to current shadow dom
this.shadow.appendChild(linkElem);
}
});
</script>
由於core.css
被調用(鏈接)兩次會影響性能嗎?
您可以嘗試使用可構造樣式表對象
通過這種方法,您可以定義全局樣式,然后將它們與shadowRoot.adoptedStylesheets
一起使用,如下所示:
import {
resetSheet,
headlinesSheet,
coreSheet,
} from '/style-system.js';
import {
myComponentStyles,
} from './styles.js';
// ...
connectedCallback() {
// Only compose styles once
if (!this.shadowRoot.adoptedStyleSheets.length) {
this.shadowRoot.adoptedStyleSheet = [
// global stylesheets
resetSheet,
headlinesSheet,
coreSheet,
// specific sheet for this component
myComponentStyles
]
}
}
與您使用的方法(為每個組件創建鏈接元素)相比,這種方法的主要優點是:
由於這是一種全新的方法,我建議您閱讀以下文章,以便對可Constructable Stylesheet Objects
有更扎實的了解
瀏覽器將緩存對core.css
的請求,因此不會真正降低性能,但由於樣式表將異步加載,因此當瀏覽器第一次獲取 css 時,您可能會看到無樣式內容 (FOUC) 的閃光。
解決此問題的一種可能方法是在文檔<head>
預加載 css 文件,以便在解析 Shadow DOM 時(可能,因為預加載只是瀏覽器的“提示”)可用:
<link rel="preload" href="core.css" as="style">
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.