February 28, 2012

Load StyleSheet dynamically with Callback function

Question by Mahan

I have this short JavaScript function that loads CSS file dynamically. But im not yet good at JavaScript so can anyone give me an idea on how can I create a callback function once the CSS file was successfully loaded…

function loadStyleSheet(url){
    if(document.createStyleSheet) {
        try {document.createStyleSheet(url);} catch (e) { }
    }
    else{
        var css;
        css         = document.createElement('link');
        css.rel     = 'stylesheet';
        css.type    = 'text/css';
        css.media   = "all";
        css.href    = url;
        document.getElementsByTagName("head")[0].appendChild(css);
    }
}

P.S. If you have an idea on how I can also know if the loading of CSS file has failed. Well i will thank you more ^_^

Answer by Starx

I think the simplest would be to append the markup to the head on load

$('<link rel="stylesheet" href="link.css" type="text/css" />').appendTo("head")
.each(function() { //little trick to create the callback fucntion
    // I am the callback
});

P.S: Its a jQuery solution. I didn’t notice JS & CSS tag, but still its a good solution

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!