![](/img/trans.png)
[英]Uncaught DOMException: Failed to execute 'addRule' on 'CSSStyleSheet': Cannot access StyleSheet to insertRule
[英]Chrome 64 Uncaught DOMException: Failed to execute 'insertRule' on 'CSSStyleSheet': Cannot access StyleSheet to insertRule
啊! 我的網站在 Chrome 中壞了。
在控制台中收到此消息: Uncaught DOMException: Failed to execute 'insertRule' on 'CSSStyleSheet': Cannot access StyleSheet to insertRule
它指向這行代碼,它來自第三方插件:
document.styleSheets[0].insertRule(rule,0);
head 中定義的樣式表:
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato:300,400,700">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css">
<link type="text/css" rel="stylesheet" href="/Public/js/jquery-ui/jquery-ui.css" />
<link type="text/css" rel="stylesheet" href="/Public/js/jquery-ui/jquery-ui.theme.min.css" />
<link type="text/css" rel="stylesheet" href="/Public/css/msgPop.css" />
<link type="text/css" rel="stylesheet" href="/Public/js/select2/select2.css">
我們認為對 Chromium 的這種承諾是我們問題的根本原因:
我們的快速解決方案是簡單地重新排序 CSS。 似乎以前罪魁禍首插件將 CSS 規則插入到這個遠程 CSS:
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato:300,400,700">
簡單地重新排序我們的樣式表以確保我們網站的腳本處於第一個位置( document.styleSheets[0]
),解決了這個問題:
<link type="text/css" rel="stylesheet" href="/Public/js/jquery-ui/jquery-ui.css" />
<link type="text/css" rel="stylesheet" href="/Public/js/jquery-ui/jquery-ui.theme.min.css" />
<link type="text/css" rel="stylesheet" href="/Public/css/msgPop.css" />
<link type="text/css" rel="stylesheet" href="/Public/js/select2/select2.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato:300,400,700">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css">
動態添加樣式標簽
class StyleSheet {
constructor(name = 'dynamic-styleSheet') {
this.styleSheet = this.getStyleSheet(name)
}
getStyleSheet(name) {
if (!document.getElementById(name)) {
const style = document.createElement('style')
style.title = name
document.getElementsByTagName('head')[0].appendChild(style)
}
let styleSheet = null
for (let i = 0; i < document.styleSheets.length; i++) {
styleSheet = document.styleSheets[i]
if (styleSheet.title === name) {
break
}
}
return styleSheet
}
insertRule(css, index) {
return this.styleSheet.insertRule(css, index)
}
deleteRule(index) {
this.styleSheet.deleteRule(index)
}
}
export default StyleSheet
// let styleSheet = new StyleSheet ()
// styleSheet.insertRule('h1{color:red;}', 0)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.