Script Loading and Dependencies

12 Jan 2010 | By Alex Young | Tags dependencies loading

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.

Dominoes

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 pages.

The following examples are from the hands on 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.

Substitution

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);

Dependencies

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)

blog comments powered by Disqus