Script loading


There’s been a fair amount of interest lately in non-blocking script downloads and various ways to load multiple scripts for which the current script has dependancies with a callback onready.

This can be a tricky problem to solve for really old browsers but if we’re only worried about modern browsers (you know, no Netscape 4.7) then the solution is fairly straightforward. I’ve supplied the code here in a library free version for those of you who don’t have their own solution, don’t want to use any of the library solutions and don’t feel the need to unwind one of those solutions to see how it works.

You can get the script from nolib.load.js.

You can call this like so:


nolib.loadAll("http://example.com/script1.js,http://example.com/script2.js").oncomplete(function() {
    alert("all scripts loaded");
});


There are also nolib.load() and nolib.insx() functions which some people may find useful. As the code is (deliberately) stripped of comments you’ll have to figure out how to use them yourself.

Update: It’s important to keep in mind that non-blocking means what it says… whilst you can sequence script insertions you don’t know (without testing) what state the page is in when you do each insertion. If you’re inserting code that adds an onload handler of some type you should be aware that your script may not get oncomplete in time - meaning your onload won’t work.



CoffeeScript in Action


CoffeeScript in Action book cover

I'm the author. Get it from Manning.