我正在检查 document.styleSheets 以确定文件是否已加载。我在做,
for (var i = 0, iLen = document.styleSheets.length; i < iLen; i++) {
var sheet = document.styleSheets[i];
if (!sheet.href) {
continue;
}
if (sheet.href.indexOf('mypath') > -1 && sheet.rules.length > 0) {
// do something
}
}
但是它不起作用。有办法吗?
最佳答案
我尝试了你的代码 ant 它对我有用(在 chrome 上,带有内部 css),但是当使用从 CDN 加载的外部 css 时它失败了,所以我猜你的问题是 @PatrickEvans 提到的“规则”属性。
如果你没有找到其他好的方法,那么你可以在页面中添加一个不影响页面显示的元素,但可以检查是否有变化。
例如像这样添加一个特定的 css 规则。
html body div#my_stylesheet_name {
width: 112px !important;//random width that is unlikely overwritten by another css
}
<div id="my_stylesheet_name" style="height:0; width: 0;display: none;"></div>
//then use javascript timer/interval to check if
element with id of "my_stylesheet_name" has width of 112, if so, then it means css has loaded.
编辑 - 如果你没有任何其他选择,你可以考虑这样的事情(我自己之前没有使用过它所以在使用它之前测试浏览器兼容性)
1) 使用 JS 创建元素
2) 添加错误和加载事件,并使用它们来施展魔法
var link;
link = document.createElement("link");
link.setAttribute("type", "text/css");
link.onload=function( evt ) {
console.log("LINK LOADED", evt );
};
link.onerror=function( evt ) {
console.log("LINK Error", evt );
};
link.setAttribute("rel", "stylesheet");
link.setAttribute("href", "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css");
document.getElementsByTagName("head")[0].appendChild(link);
关于javascript - 使用 document.styleSheets 检查是否加载了 css 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30596857/