JavaScript Asynchronous Module Definition (AMD)


Example

AMD is a module definition system that attempts to address some of the common issues with other systems like CommonJS and anonymous closures.

AMD addresses these issues by:

  • Registering the factory function by calling define(), instead of immediately executing it
  • Passing dependencies as an array of module names, which are then loaded, instead of using globals
  • Only executing the factory function once all the dependencies have been loaded and executed
  • Passing the dependent modules as arguments to the factory function

The key thing here is that a module can have a dependency and not hold everything up while waiting for it to load, without the developer having to write complicated code.

Here's an example of AMD:

// Define a module "myModule" with two dependencies, jQuery and Lodash
define("myModule", ["jquery", "lodash"], function($, _) {
    // This publicly accessible object is our module
    // Here we use an object, but it can be of any type
    var myModule = {};

    var privateVar = "Nothing outside of this module can see me";

    var privateFn = function(param) {
        return "Here's what you said: " + param;
    };

    myModule.version = 1;

    myModule.moduleMethod = function() {
        // We can still access global variables from here, but it's better
        // if we use the passed ones
        return privateFn(windowTitle);
    };

    return myModule;
});

Modules can also skip the name and be anonymous. When that's done, they're usually loaded by file name.

define(["jquery", "lodash"], function($, _) { /* factory */ });

They can also skip dependencies:

define(function() { /* factory */ });

Some AMD loaders support defining modules as plain objects:

define("myModule", { version: 1, value: "sample string" });