简体   繁体   中英

Check css file loaded or not using document.styleSheets

I am checking document.styleSheets for finding whether the file is loaded or not. I am doing,

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
    }
}

But its not working. Is there a way?

I tried your code ant it works for me, ( on chrome, with internal css ), but it fails when using external css loaded from CDN's, so i would guess your problem is "rules" property as mentioned by @PatrickEvans.

If you don't find any other good way, then you may add an element to the page that doesn't affect the page display, but can be checked for a change.

eg add a specific css rule like this.

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.

Edit - If you dont have any other option, you may consider something like this ( i havent used it myself before so test browser compatibility before using it )

1) create the element using JS

2) add on error and onload events, and use those to do your magic

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM