0

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?

ozil
  • 6,930
  • 9
  • 33
  • 56
Imran Qadir Baksh - Baloch
  • 32,612
  • 68
  • 179
  • 322

1 Answers1

1

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.

e.g 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);
Rainer Plumer
  • 3,693
  • 2
  • 24
  • 42