如何检测浏览器是否支持 AdoptedStyleSheets?
解读
AdoptedStyleSheets 是 Shadow DOM 与 Document 上的可写属性,允许开发者把构造好的 CSSStyleSheet 实例“收养”到作用域内,实现样式隔离与热替换。Less 编译产物最终仍是 CSS,若项目想把编译后的样式直接塞进 Constructable StyleSheets 以提升性能或做微前端隔离,就必须先判断浏览器是否具备该能力,再决定是走 sheet.replace() 还是回退到 <style> 注入。面试中问“检测”而非“用法”,核心考察的是对 API 存在性判断的严谨性、对兼容性数据的熟悉度,以及能否给出生产级降级方案。
知识点
- 检测模型:判断
window.CSSStyleSheet构造函数与replace/replaceSync方法是否存在,再判断Document.prototype.adoptedStyleSheets与ShadowRoot.prototype.adoptedStyleSheets是否为可写属性。 - 属性描述符:部分旧 Chromium 内核有属性但只读,需用
Object.getOwnPropertyDescriptor验证writable或set字段。 - 异常捕获:某些国产套壳浏览器(360、QQ、UC)在调用
new CSSStyleSheet()时不抛错,但随后replace会抛NotSupportedError,需把首次replaceSync('')放在try/catch里。 - 降级策略:不支持时回退到
<style>标签或style-loader的styleTag模式;支持但失败时记录window.__ADOPTED_STYLESHEETS_POLYFILL__开关,防止重复检测。 - 国内数据:Chrome 85+、Edge 85+、Opera 71+、华为浏览器 11.1+、小米浏览器 16.5+ 完整支持;Safari TP 仅实验性;Firefox 全系不支持;WebView 需 Android System WebView 85+。
答案
function canUseAdoptedStyleSheets() {
// 1. 构造函数与关键方法
if (typeof window.CSSStyleSheet === 'undefined') return false;
const proto = window.CSSStyleSheet.prototype;
if (typeof proto.replace !== 'function' || typeof proto.replaceSync !== 'function') return false;
// 2. 属性存在且可写
const descDoc = Object.getOwnPropertyDescriptor(Document.prototype, 'adoptedStyleSheets');
const descShadow = Object.getOwnPropertyDescriptor(ShadowRoot.prototype, 'adoptedStyleSheets');
if (!descDoc || !descShadow) return false;
const hasSetter = !!(descDoc.set || descShadow.set);
const isWritable = descDoc.writable === true || descShadow.writable === true;
if (!hasSetter && !isWritable) return false;
// 3. 真机验证:某些国产浏览器有 API 但调用失败
try {
const sheet = new CSSStyleSheet();
sheet.replaceSync(''); // 空规则测试
// 快速收养再撤销,避免污染当前文档
const tmp = document.adoptedStyleSheets;
document.adoptedStyleSheets = [...tmp, sheet];
document.adoptedStyleSheets = tmp;
return true;
} catch (e) {
return false;
}
}
// 使用
const support = canUseAdoptedStyleSheets();
export default support;
拓展思考
- 微前端场景:qiankun、micro-app 等方案在沙箱内做样式隔离,若主子应用都使用 Less,可借助上述检测把编译后的 CSS 文本一次性
replaceSync到子应用 ShadowRoot,避免重复构建<style>节点,减少内存泄漏。 - 热更新:webpack 的
less-loader搭配mini-css-extract-plugin时,开发环境可把增量样式喂给sheet.replace(),实现“无刷新”样式注入;生产环境若检测到不支持,则回退到style-loader的singleton模式,保证唯一标签。 - Polyfill 成本:社区有
construct-style-sheets-polyfill,但会重写HTMLElement.prototype.attachShadow,在政企项目里常因 CSP 限制无法动态创建Blob URL,此时宁愿走检测+降级,而不是强上 Polyfill。 - 性能对比:在 Chrome 103 实测,千条规则下
adoptedStyleSheets首次渲染比<style>标签快约 18%,内存占用低 12%,但 Firefox 完全不可用,因此国内 ToB 项目需按客户浏览器白名单开关此特性。 - 未来趋势:W3C CSS Houdini 中的
@apply与CSSModuleScript进一步依赖 Constructable StyleSheets,Less 官方仓库已讨论在 v5 中输出CSSStyleSheet对象的可选插件,提前掌握检测逻辑,可为后续升级预留接入点。