Search code examples
javascriptajaxarchitectureorganization

What is the proper way to structure/organize javascript for a large application?


Let's say you are building a large application, and you expect to have tons of javascript on the site. Even if you separated the javascript into 1 file per page where javascript is used, you'd still have about 100 javascript files.

What is the best way to keep the file system organized, include these files on the page, and keep the code structure itself organized as well? All the while, having the option to keep things minified for production is important too.


Solution

  • Personally I prefer the module pattern for structuring the code, and I think this article gives a great introduction: http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth

    It keeps my global scope clean, enables namespacing and provides a nice way to seperate public and private methods and fields.

    I'd structure the code in separate files, and seek to keep coupling low and cohesion high. Although multiple files are bad for client performance (you should minimize the number of requests), you'll easily get the best from both worlds using a compression utility.

    I've some experience with YUI Compressor (for which there is a Maven plugin: http://alchim.sourceforge.net/yuicompressor-maven-plugin/compress-mojo.html - I haven't used this myself). If you need to order the javascript files in a certain way (also applies for CSS), you could make a shell script, concatenating the files in a given order in advance (Tip: YUI Compressor defaults to STDIN).

    Besides, either way you decide to minify your files will probably do just fine. Your focus should instead be on how you structure your code, so that it performs well on the client (should be highest priority in order to satisfy a good UX), and is maintainable in a way that works for you.

    You mention namespaces, which is a good idea, but I'd be careful to adopt too many concepts from the traditional object oriented domain, and instead learn to utilize many of the excellent features of the javascript language :)