Home > Architecture, Programming > Modular JavaScript

Modular JavaScript

This post is part of a series of posts on Client-Side Web Application Development using JavaScript.


I read this quote somewhere, I cannot recall, But it best echoes the sentiments about modular applications.

The best way to write a large-scale application is by not writing one, instead choose to implement small rightly coupled modules

The goals

  • Do not pollute the global namespace
    • Avoid namespace collisions
  • Load modules fast (even out of order, given the asynchronous nature of the browser)
  • Execute / Evaluate modules in the right order


Script Loaders load scripts asynchronously and module libraries handle dependencies, that does not mean that we leave performance out of the equation and load 20 JavaScript files asynchronously with round-trips to the server. Nor does it mean to dump all the JavaScript required for the page in one single file. Most of the module libraries use a optimization tool that can bundle all the scripts into a single file for deployment. Example requirejs used r.js and curl.js uses cram. It may be good idea still to leave it to the Script Loader implementation of the Module Library when the scripts are conditionally required (for ex: a Canvas library to mimic HTML5 canvas in a older browser).


So we decided to implement modular JavaScript in our application, rather inventing a way for ourselves to implement modules in JavaScript we can choose to embrace one of the following standards.

  • Asynchronous Module Definition format (AMD)
  • CommonJS (CJS) module format
  • Node (though this is not a standard you can consider this as a slightly modified version of CJS. I hope CJS adopts the additional features from Node)


Which one should my application use, I will use the following recommendation (slightly modified for node) from John Hann’s blog post.

    1. write modules that could execute in a server environment in CJS
    2. write modules that could benefit from AMD’s browser-friendly features in AMD format

    What if you need a module to executed in both client and server? Use requirejs to run AMD in node instead of using Node’s inbuilt module loader and module format? The solutions like onejs / browserify seem like too much magic to me.

    Reading list







    Leave a Reply

    Fill in your details below or click an icon to log in:

    WordPress.com Logo

    You are commenting using your WordPress.com account. Log Out / Change )

    Twitter picture

    You are commenting using your Twitter account. Log Out / Change )

    Facebook photo

    You are commenting using your Facebook account. Log Out / Change )

    Google+ photo

    You are commenting using your Google+ account. Log Out / Change )

    Connecting to %s

    %d bloggers like this: