Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

css

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

like image 209
Abdul Munim Avatar asked Sep 25 '10 14:09

Abdul Munim


1 Answers

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");
})
like image 113
letronje Avatar answered Sep 21 '22 08:09

letronje