[英]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.