Asset.css claims to have an onload event in Mootools documentation, but sadly, not all browsers support this feature. Even worse, browsers like Chrome seem to support the event, but never fire it.
After some research and testing at work, we have come up with a solution that overrides Asset.css to detect when CSS gets loaded by the browser using the onload event in those browsers that support it (Internet Explorer and Opera) and doing polling in those that do not (Chrome, Safari and Firefox). Here is the code:
-
// Add callback support to Asset.css for all browsers
-
Asset.css = function(source, onLoad) {
-
var link = new Element('link', {
-
rel: 'stylesheet',
-
media: 'screen',
-
type: 'text/css',
-
href: source
-
});
-
-
if (("onload" in link) && !Browser.Engines.webkit()) {
-
if (onLoad) link.onload = onLoad;
-
} else {
-
(function() {
-
try {
-
link.sheet.cssRules;
-
} catch (e) {
-
setTimeout(arguments.callee, 100);
-
return;
-
};
-
if (onLoad) onLoad();
-
})();
-
}
-
-
link.inject(document.head);
-
return link;
-
}
-
-
// Load some CSS and show an alert when done
-
var mycss = new Asset.css('http://example.com/style.css', function() {
-
alert('CSS loaded!');
-
});
-
-
// Unload the css
-
mycss.destroy();
Enjoy!
