Capturing load event on LINK

Here’s what is, in my opinion, a better solution for this issue that uses the IMG tag and its onerror event. This method will do the job without looping, doing contorted style observance, or loading files in iframes, etc. This solution fires correctly when the file is loads, and right away if the file is already cached (which is ironically better than how most DOM load events handle cached assets). Here’s a post on my blog that explains the method – Back Alley Coder post – I just got tired of this not having a legit solution, enjoy!

var loadCSS = function(url, callback){
    var link = document.createElement('link');
        link.type="text/css";
        link.rel="stylesheet";
        link.href = url;

    document.getElementsByTagName('head')[0].appendChild(link);

    var img = document.createElement('img');
        img.onerror = function(){
            if(callback) callback(link);
        }
        img.src = url;
}

Leave a Comment