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
142 views
in Technique[技术] by (71.8m points)

HOW TO check if an external (cross-domain) CSS file is loaded using Javascript

I have a function doing the following using javascript:

  1. Create link element and set href=cssFile.
  2. Insert the link element in head tag.
  3. Create a div element.
  4. Set the class name using setAttribute
  5. appendChild the div on body.
  6. Now getting CSS rule value using document.defaultView.getComputedStyle(divElement, null)[cssRule].

Now getComputedStyle is returning the default values, and if I wait on breakpoint using Firebug before getComputedStyle call, then it returns the CSS rule from the CSS injected.

Regards,
Munim

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You can create the dynamic css url and fetch the css as plain text using a normal ajax call.

Then use this to load the css:

function loadCss(cssText, callback){
    var style = document.createElement('style');
    style.type='text/css';
    if(callBack != undefined){
        style.onload = function(){
            callBack();
        };
    }
    style.innerHTML = cssText;
    head.appendChild(style);
}

And use it like this:

loadCss(ajaxResponseText, function(){
    console.log("yaay css loaded, now i can access css defs");
})

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

...