Archive for January, 2012

mod – A javascript module definition and loading tool.

Wednesday, January 18th, 2012

Now that I’ve been writing a lot less Actionscript and a lot more Javascript I’ve found that I often need a system for separating my code out into modules. Javascript doesn’t provide a convenient way to load scripts and define modules so I wrote a tool I call ‘mod‘ that uses either XMLHTTPRequests or script tag injection to load scripts.

mod uses initialization objects to define modules. A module object takes a name, an init function and optionally an array of dependencies (paths to other scripts you’d like to load before initializing the current module). You can also supply an optional callback to execute after the module has been initialized. Both init() and callback() are passed an object that contains all the initialized modules thus far.

Defining a module looks like this:

    name : 'Main',
    dependencies : [
    init : function initMain(modules) {
        // we can access anotherModule because mod.js
        // loads and initializes dependencies in order
        var anotherModule = modules.anotherModule;
        return {
            someValue : anotherModule.someFunction(),
            functionToExpose : anotherModule.someFunctionToExpose
    callback : function cbMain(modules) {
        // we can access Main because callback() is not called
        // until after Main's init()
        var Main = modules.Main;
        window.exposedFunction = Main.functionToExpose;

In this first call mod packages your module initialization object and starts loading its dependencies (either through XMLHttpRequest or script tag injection). Once the dependencies are loaded (which may or may not define more modules and load more scripts), the result of the init function is stored in mod.modules, in this case as mod.modules.Main. The loaded modules are exposed to your init and callback functions as the only parameter, so they don’t clutter global space. As an added benefit, you can share data between modules using mod.modules.

If you use mod to write lots of modules (like I do when working on a big project), mod can ‘compile’ your project for you, removing all script loading. It essentially takes all your init and callback functions, wraps them inside an island closure and prints them to one monolithic file which you can then compress with YUI or a google ‘something-or-other’.
To do this, load your project in your browser, open the js console and type mod.printCompilation(). Alternatively, to store in a string, type var compilation = mod.compile();.

Follow me on GitHub
Follow me on Google+
Follow me on Twitter