概述Constructable Stylesheets 允许通过 `new CSSStyleSheet()` 构建样式并在多个根(文档/Shadow DOM)间复用,避免重复 `<style>` 注入与字符串拼接,改善组件样式管理与性能。示例const sheet = new CSSStyleSheet() await sheet.replace(`.btn{padding:8px 12px;border-radius:8px}`) document.adoptedStyleSheets = [...document.adoptedStyleSheets, sheet] class XCard extends HTMLElement { constructor(){ super(); const root = this.attachShadow({ mode:'open' }); root.adoptedStyleSheets = [sheet]; root.innerHTML = '<button class="btn">OK</button>' } } customElements.define('x-card', XCard) 工程建议复用与拆分:将通用样式拆分为多个 `CSSStyleSheet`;按组件导入,减少重复。动态更新:使用 `replace`/`replaceSync` 更新样式;控制更新频率以避免布局抖动。兼容:旧浏览器回退到 `<style>` 注入;通过构建工具或运行时分支处理。参考与验证MDN CSSStyleSheet 文档:https://developer.mozilla.org/docs/Web/API/CSSStyleSheetChrome 平台文档(Adopted StyleSheets):https://developer.chrome.com/docs/web-platform/constructable-stylesheets/web.dev 指南:https://web.dev/articles/constructable-stylesheets

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论
立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部