Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
184 views
in Technique[技术] by (71.8m points)

javascript - Dynamically loading CSS

I'm trying to create a page theme function for my site. I want to load the corresponding themes dynamically on the page using separate CSS files.

I'm using this code:

  fileref.setAttribute("rel", "stylesheet")
  fileref.setAttribute("type", "text/css")
  fileref.setAttribute("href", 'link.css')

  document.getElementsByTagName("head")[0].appendChild(fileref)

Which works fine, but it doesn't return any info if the CSS file has loaded or not.

Is there a way to catch when the .css is loaded? Maybe by using ajax?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Internet Explorer will trigger an onReadyStateChange event when CSS file is loaded (or any other change in it's readyState). Other browsers do not trigger any event, so you will have to manually check if the stylesheet has been loaded, which is easily possible by checking the document.styleSheets object at a fixed interval.

Example

window.onload = function (){
    var filename = "link.css",sheet,i;
    var fileref = document.createElement("link");

    fileref.setAttribute("rel", "stylesheet");
    fileref.setAttribute("type", "text/css");
    fileref.setAttribute("href", filename);

    readyfunc = function () {
        alert("File Loaded");
    }

    timerfunc = function (){
        for (i=0;i<document.styleSheets.length;i++){
            sheet = document.styleSheets[i].href;
            if(sheet !== null && sheet.substr(sheet.length-filename.length) == filename)
                return readyfunc();
        }
        setTimeout(timerfunc,50);  
    }

    if (document.all){ //Uses onreadystatechange for Internet Explorer
        fileref.attachEvent('onreadystatechange',function() {
            if(fileref.readyState == 'complete' || fileref.readyState == 'loaded')
                readyfunc();
        });
    } else {    //Checks if the stylesheet has been loaded every 50 ms for others
        setTimeout(timerfunc,50);
    }
    document.getElementsByTagName("head")[0].appendChild(fileref);    
}

It's ugly, but it works in all browsers.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...