2

I have used a technique described in a post on StackOverflow to dynamically add a CSS file to the HEAD tag of an HTML page (in JavaScript). The method to check whether the CSS file has been fully loaded (see the same post) is described by its author as 'ugly' and in my opinion it is ;-) Yet another post suggests using a 'lazy loader' (see the accepted answer in that post) that takes cross-browser issues into account. Though the code looks fine, is seems rather complex for the task at hand.

My question is: More than a year after the post that I have last mentioned (and a lot of improvements in browser techniques), is there a reliable, cross-browser way to check whether a dynamically loaded CSS file is ready to use?

Community
  • 1
  • 1
Jeroen
  • 809
  • 12
  • 20

2 Answers2

0

You can achieve it by loading your CSS file with an img.

var img = document.createElement("img");

img.onerror = function()
{
    console.log("loaded");
}

img.src = url;

More information here: http://www.backalleycoder.com/2011/03/20/link-tag-css-stylesheet-load-event/

Steven Vachon
  • 3,168
  • 1
  • 21
  • 29
0

try something like this

(function() {
    function cssLoader(url) {
        var link = document.createElement("link");
        link.onload = function(){
            console.log('loaded');
        };
        link.setAttribute("rel", "stylesheet");
        link.setAttribute("type", "text/css");
        link.setAttribute("href", url);
        document.getElementsByTagName("head")[0].appendChild(link)
    }

    cssLoader('http://jsfiddle.net/css/style.css');

}());​
Joseph
  • 107,072
  • 27
  • 170
  • 214
  • 1
    I have tried the jsFiddle, but it doesn't seem to work in Chrome (17) and IE 9. I don't think those browsers actually support the onload event on a (dynamic) link element. I think at least IE needs the onreadystatechange event. The lazy loader that I have mentioned in my question (https://github.com/LukeTheDuke/Lazyloader/blob/master/lazyloader.js) uses both onload and onreadystatechange. – Jeroen Mar 29 '12 at 14:39