tags:

views:

69

answers:

2

Hi Guys,

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

+1  A: 

I assume you are doing this because you need to dynamically create the URL of the stylesheet.

Couple options come to mind:

1) Create the URL server-side and avoid this problem altogether.

2) Use a setTimeout to check whether or not the style has been loaded and check every 20ms or so until getComputedStyle returns the value you want.

I don't like #2 at all...but it's an option. If you use #2 make sure to clear the timeout even if there is an exception.

Tim
+2  A: 

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");
})
letronje
+1 for this solution. I prefer it to the one I proposed, assuming all browsers can interpret a dynamically added style tag (haven't tried it).
Tim
Thanks for the solution! But one thing that I forgot to mention in the question, and that is my CSS is on other domain... Meaning, a cross-browser issue with no ajax response
Munim Abdul
@Munim: if the css is on another domain, try adding the 'link' tag (to head) with the appropriate type, rel and href and onload function. Let me know if it works.
letronje
@letronje: Thanks for your concern, but onload @ `link` does not work
Munim Abdul