How can I split a javascript application into multiple files?

Take a look at the design pattern in this article: http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth – you can split your module definition across multiple files in a way that lets common properties be shared but also lets you create variables or methods that are private just to a particular file.

The basic idea is that the individual JS files add to the same module with code like this:

var MODULE = (function (my) {
     var privateToThisFile = "something";

    // add capabilities...

     my.publicProperty = "something";

    return my;
}(MODULE || {}));

Where in each JS file if MODULE is already defined (from another JS file) you add to it otherwise you create it. You can set it up so that it (mostly) doesn’t matter what order the various files are included in.

The article details several variations, and of course you’ll probably come up with your own tweaks…

Leave a Comment