Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change css link and wait till new css is loaded

I wonder whether it's possible to change stylesheet link of the loaded document, then wait till the new css is loaded, and then run appropriate js code

thanks for any suggestions

like image 704
gruber Avatar asked Sep 04 '12 22:09

gruber


2 Answers

@ahren had it almost correct. However using a callback when the css file is finished loading via dynamically changing the href on a link element DOES NOT seem to work on most mobile devices.

Instead try directly injecting the style into a style element using load .. ends up being supported by most modern browsers including mobile ones

UPDATED to include support for IE 8- ; NOTE this requires you to inject a dummy rule into your css to verify when the css is loaded (in this case use body {ready:true;})

css

body {ready:true;}
...

html

<style id="your-style-element"></style>

javascript

if (document.createStyleSheet) {

    //Wait for style to be loaded
    var wait = setInterval(function(){
      //Check for the style to be applied to the body
      if($('body').css('ready') === 'true') {
        clearInterval(wait);

        //CSS ready
      }
    }, 300);

    document.createStyleSheet(url);
} else {
    //Dynamically load the css for this doc
    $("#your-style-element").load(url,function(){

       //CSS ready
    });
}
like image 22
Chad Brown Avatar answered Sep 19 '22 10:09

Chad Brown


html:

<link id="mystylesheet" href="/path/to/css.css" />

code:

$("#mystylesheet").load(function(){
  //Your javascript
}).attr("href", "/new/path/to/css.css");

This will replace your current CSS, and execute any code within the .load() handler after the new CSS file has been fetched.

like image 145
ahren Avatar answered Sep 22 '22 10:09

ahren