Jul 232008
 

Stoyan Stefanov writes about Non-Blocking JavaScript Downloads on the Yahoo User Interface Blog.  Good content all around, but I’d like to add a note on an item he somewhat casually skimmed over.

In the “Dependencies” section of the article, Stefanov describes using the onLoad or onReadyStateChange events of the dynamically generated script tag to receive notification when that script has been loaded by the browser.  Once you know it’s loaded, then you know it’s safe to begin using the code it contains.

This works great for Firefox and IE, but fails completely in the Safari browser.  Safari doesn’t implement onLoad notifications for script tags.  This forces you to abandon the onLoad technique and instead use the technique of embedding something at the end of each script file to signal when the file has been loaded. 

The script libraries for the Windows Live sites use this technique – every source file contains a function call at the bottom that tells a central notifier that it has been loaded.  Other code can ask the notifier to signal them when a file or set of files have been loaded.  This works in all browsers without relying on diverging browser idiosyncracies. 

Unfortunately, this also requires that all the JavaScript you want to load dynamically (using this technique) knows about your particular load notification pattern.  If you want to dynamically load JavaScript from multiple libraries or authors, you will either end up with multiple notification systems (which should coexist peacefully) or you’ll have to modify those files to use your load notifier.  This is bad from a design standpoint because it requires that all your code modules have carnal knowledge of your application – erodes the modularity of the source files – or require that all your code modules follow the design patterns of a particular JavaScript toolkit, like DoJo or Prototype or YUI.  The latter isn’t a terrible tradeoff except that it limits your options.

 Discovered via a note by Steve Trefethen on FriendFeed.