【问题标题】:Check css file loaded or not using document.styleSheets使用 document.styleSheets 检查是否加载了 css 文件
【发布时间】:2015-06-03 01:50:06
【问题描述】:

我正在检查 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
    }
}

但它不起作用。有什么办法吗?

【问题讨论】:

标签: javascript css


【解决方案1】:

我尝试了您的代码 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);

【讨论】:

  • @user960567 用另一个潜在的解决方案更新了我的帖子
猜你喜欢
  • 2011-05-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-27
  • 1970-01-01
  • 1970-01-01
  • 2011-11-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多