Detect when a stylesheet finishes loading

  • 8/9/2011

Sometimes it’s nice to be able to trigger an action when a resource is loaded, usually by simply attaching a handler to the resource’s onload event. Unfortunately, the implementation of onload for <link> elements is notoriously inconsistent across browsers. Plenty of browser-specific hacks exist to check if a stylesheet has loaded in a specific browser, but their longevity as browsers and standards develop is anybody’s guess.

A slightly less brittle approach is to create a “beacon” element whose appearance will change once the stylesheet is loaded. This shifts the approach away from using browser-specific techniques to detect the stylesheet itself, and towards the affects that the stylesheet is having. Here’s how it’s done.

At the very end of the stylesheet to be loaded (test.css), create a rule for the beacon element. Something along the lines of:

#beacon { 

Somewhere in the body of the page, add a beacon element and a test to check if the custom rule has been applied to it:

<div id="beacon"></div>

var head = document.getElementsByTagName( 'head' )[0];
var handle = window.setInterval( function(){
    if( document.getElementById('beacon').clientWidth==42 ) {
        alert('script file has loaded');
        // ... do stuff
}, 30 );

Finally, dynamically link the stylesheet containing the #beacon rule:

var style = document.createElement( 'link' );
    style.rel = 'stylesheet';
    style.href = 'test.css';

When the new stylesheet loads, the change in the beacon element’s width will be detected by the polling function.