i\'m trying to attach an event handler to the load event of a link tag, to execute some code after a stylesheet has loaded.
new_element = document.createElem
All credit goes to Tobiasz up above, but here's a little expansion on what he said:
function _cssIsLoaded(cssStylesheet) {
var cssLoaded = 0;
try {
if ( cssStylesheet.sheet && cssStylesheet.sheet.cssRules.length > 0 )
cssLoaded = 1;
else if ( cssStylesheet.styleSheet && cssStylesheet.styleSheet.cssText.length > 0 )
cssLoaded = 1;
else if ( cssStylesheet.innerHTML && cssStylesheet.innerHTML.length > 0 )
cssLoaded = 1;
}
catch(ex){ }
if(cssLoaded) {
// your css is loaded! Do work!
// I'd recommend having listeners subscribe to cssLoaded event,
// and then here you can emit the event (ie. EventManager.emit('cssLoaded');
} else {
// I'm using underscore library, but setTimeout would work too
// You basically just need to call the function again in say, 50 ms
_.delay(_.bind(this._cssIsLoaded, this), 50, cssStylesheet);
}
}
You'd call it with something like (using jquery):
var link = $("");
link.attr({
type: 'text/css',
rel: 'stylesheet',
href: sheet
});
$("head").append(link);
// link.get(0), because you want the actual element, not jQuery-wrapped element
self._cssIsLoaded(link.get(0));