Includes and dependencies in Javascript
For a while now I have been wrestling with a way to easily manage dependencies in Javascript.I absolutely hate having a mess of script tags in my documents, especially on a dynamic page that only uses maybe one or two of those scripts.
So when I started using jQuery, I was delighted to find that I could write an easy method to include files on the fly using Ajax and synchronous loading and execution of Javascript files. This gives us the ability to utilize lazy-loading to load scripts as they are needed and not clutter up things or waste resources if a particular Javascript is not needed.
It is easy to define a method like this (utilizing a class so as not to pollute the main Javascript namespace):
SLAGGLE = function() {};
SLAGGLE.include = function(filename) {
$.ajaxSetup( { async: false } );
$.getScript(filename);
$.ajaxSetup( { async: true });
};
This uses jQuery’s getScript method to load a script, but first sets global Ajax configurations to load it synchronously so we can use it right away. So now if I want to load a script on the fly, I can do so with this:
SLAGGLE.include('/path/to/js/script.js');
You can even go a lot further and create a method to translate a package heirarchy like what Java uses into a path structure and load that instead.
I’ve been using this method for a while, but this morning I stumbled across this: using.js
using.js gives stronger dependency management to Javascript by allowing you to declare potential dependencies beforehand, and load them on the fly. The upside to doing this is that not only do you get lazy-loading, but the using.js script will only load a particular dependency only once, which cuts down on overhead quite a bit. It’s real easy to use, too. Just register your dependency like this:
using.register("jquery", "/path/to/jquery-1.2.3.js");
or even multiple dependencies:
using.register("yui-datatable",
"/path/to/yui/script1.js",
"/path/to/yui/script2.js"
);
Then later, when you need to make use of the dependency, you can do the following:
using("jquery");
// Use jQuery features
$("document").ready(function() {});
using("yui-datatable");
// Use YUI features, etc...
The using.js script really adds a lot of power to your Javascript coding. It has the potential to make your code much more efficient if you rely on a large number of external dependencies. Give it a try and let me know what you think!