having fun with code

Detecting when CSS gets loaded by the browser with Mootools and Asset.css

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:

  1. // Add callback support to Asset.css for all browsers
  2. Asset.css = function(source, onLoad) {
  3.   var link = new Element('link', {
  4.     rel: 'stylesheet',
  5.     media: 'screen',
  6.     type: 'text/css',
  7.     href: source
  8.   });
  9.  
  10.   if (("onload" in link) && !Browser.Engines.webkit()) {
  11.     if (onLoad) link.onload = onLoad;
  12.   } else {
  13.     (function() {
  14.       try {
  15.         link.sheet.cssRules;
  16.       } catch (e) {
  17.         setTimeout(arguments.callee, 100);
  18.         return;
  19.       };
  20.       if (onLoad) onLoad();
  21.     })();
  22.   }
  23.  
  24.   link.inject(document.head);
  25.   return link;
  26. }
  27.  
  28. // Load some CSS and show an alert when done
  29. var mycss = new Asset.css('http://example.com/style.css', function() {
  30.   alert('CSS loaded!');
  31. });
  32.  
  33. // Unload the css
  34. mycss.destroy();

Enjoy!

Related Posts:

Leave a Reply

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Additional comments powered by BackType

About the blog

This is a blog about development, focused mainly on Javascript but also other languages like python, shell scripts and more.

About the author

Eneko Alonso is a software engineer and UI developer with more than eight years of experience in software and web development. He lives in San Luis Obispo, California and works at LEVEL Studios.

Contact Info

Contact Info

PromoteJS

JavaScript JS Documentation