Script Loading and Dependencies

2010-01-12 00:00:00 +0000 by Alex R. Young

I've created a few projects that are self-contained HTML/JavaScript
files -- small utilities that are easy to share or stash on a USB stick.
When writing this type of project I like to use a script loader like
Google's AJAX Libraries so I don't need to bundle separate files. Another use case is for very
complex projects: Google's API allows you to easily switch between
different library versions which is great for testing against a new
version of a big library like jQuery.


If you have a place to host code you might still want to use a script
loader. I've recently been looking at
javascript-dominoes which includes script loading, aliasing and dependencies. The dependency
engine in particular allows you to express rules that permit scripts to
be loaded concurrently, which could improve the load times of your

The following examples are from the hands

documentation on the javascript-dominoes site.

Script Loading

Basic usage is like this:

dominoes("http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" , function() {
    // jQuery dependant code goes here
} );

If this is called twice dominoes will automatically detect that the
script has already been loaded.


Properties can be defined to shorten configuration:

dominoes.property("mySiteJSPath" , "http://mySite.org/u/kio/67/long/is/long/js");
dominoes("${mySiteJSPath}/script1.js" , function1);


If you have a script that does not depend on jQuery, you can tell
dominoes to concurrently load the scripts:

dominoes("${jQueryURL} ./js/myScript/js" , myFunction);

Dependencies can be expressed using operators:

action1 action2 action1 & action2 are independant
action1 > action2 action2 depends on the completion of action1
action1 >| action2 action2 depends on the completion of action1 and on the DOM being ready for manipulation
{ sub-rule } sub-rule (the completion of this action is determined by the completion of the whole sub-rule)
{{ "{{" }} optional-sub-rule }} optional sub-rule (same as a normal sub-rule but the completion of this action is not needed down the line, i.e. fire & forget)