簡體   English   中英

使用document.styleSheets檢查是否已加載css文件

[英]Check css file loaded or not using document.styleSheets

我正在檢查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)添加錯誤和onload事件,並使用它們做你的魔術

    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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM