views:

145

answers:

1

Browsers provide load events for <script> and <img> tags. Is there a way to detect whether a request to a element has completed?

Specifically, I'm wishing to detect when a <link>'d stylesheet has been loaded.

Unfortunately, I think using a sentinel style and detecting load from a computedStyle isn't workable in my situation.

+1  A: 

There may be a simpler way to do it, but this worked for me.

Make sure your <link> tag has a title attribute:

<link title="myStyles" rel="stylesheet" href="style.css" />

Then use a function like this to check for the presence of a style within a particular styleseet:

function linkLoaded(linkTitle, checkStyle)
{
    for (var ix=0; ix<document.styleSheets.length; ix++) {
        try {
            if (document.styleSheets[ix].title == linkTitle) {
                var mySheet=document.styleSheets[ix];
                var myRules = mySheet.cssRules? mySheet.cssRules: mySheet.rules
                for (var jx=0; jx<myRules.length; jx++) {
                    var thisSelector = myRules[jx].selectorText.toLowerCase();
                    if (thisSelector.substring(0, checkStyle.length) == checkStyle) {
                        alert("Found style!");
                        return;
                    }
                }
            }
        }
        catch (err) {}    
    }

    alert("Not loaded!");
    return;
}
Steven Richards