When I’m developing small or medium or large javascript projects I end up with the same problem all the time: code grows and it starts getting a mess if you don’t do something about it. The only way out is separating your code into different modules which leads to the only conclusion of separating it on different files.
Most javascripts frameworks use different approaches to this. Some use an offline builder to create a single javascript file they distribute. Some other use a online dependency loading through different methods and some others a combination of both. Here’s a small list of frameworks and what they do:
YUI Loader Utility
If you plan to use the YUI Loader Utility, it means that you’ll have to add it to your page, in other words 9.4kb more, not too bad. You can load any javascript file. It also supports rolled up files, this means that you can have all the source files “rolled up” on one file and the loader works exactly the same way as if you were using separate files. This is an online only loader. It looks like this:
var loader = new YAHOO.util.YUILoader({ require: ["colorpicker", "treeview"], }); loader.insert();
For custom modules it looks like this:
loader.addModule({ name: "json", type: "js", fullpath: "http://www.json.org/json2.js", varName: "JSON" });
Dojo Toolkit
This choice means that you’ll have to build over dojo and use dojo’s require and provide mechanisms to request and provide modules online. It also has a ant and rhino based build system that can pack offline all modules in one file. The base dojo script takes ~100kb compressed which is quite large. I’m not really sure if the build system would work without the base dojo.js file. It looks like this:
dojo.require("dijit.form.Button");
And the module file, in this case by default at dijit/form/Button.js, should start with:
dojo.provides("dijit.form.Button");
Prototoype
The Prototype build system uses Rake. This approach has the benefit of having multiple source javascript files and through a build system combine them on a single file. The downside is that you cannot choose at runtime which modules to load or not making it a all-or-nothing package. Also while developing you’ll need a ruby server to be able to test your code without compiling it. The code you need looks like this:
<%= include 'lang/class.js', 'lang/object.js' %>
Note that it is not javascript but ruby code.
Mochikit
The Mochikit build system is based on python and rhino. It’s an offline packer and for development you’ll have to add all the scripts you are developing and dependencies on the right order. It has some sort of validation of import like this:
MochiKit.Base._module('Format', '1.5', ['Base']); ... MochiKit.Base._exportSymbols(this, MochiKit.Format);
In the next article I’ll write about the internal methods used to load javascript files online, their advantages and disadvantages as well as my own way of doing it.