AMD loader in 30 lines of code

comment

The code below implements a simple AMD loader that uses native JavaScript Promises to do the heavy lifting.

Both Chrome (version 33) and Firefox (version 29) support promises by default.

To run the example your browser has to support:

var registry = {
    promises: { },
    resolves: { },
    getDependencyPromise: function(name) {
        if (!this.promises[name]) {
            var resolves = this.resolves;
            this.promises[name] = new Promise(function(resolve) {
                resolves[name] = resolve;
            });
        }
        return this.promises[name];
    },
    resolve: function(name, value) {
        this.getDependencyPromise(name); // create promise if necessary
        this.resolves[name](value);
        delete this.resolves[name];
    }
};

function define(name, deps, definition) {
    require(deps, function() {
        registry.resolve(name, definition.apply(this, arguments));
    });
}

function require(deps, definition) {
    var promises = deps.map(registry.getDependencyPromise, registry);
    Promise.all(promises).then(function(result) {
        definition.apply(this, result);
    });
}

define('framework', ['component', 'library'], function(cmp, lib) {
    return { init: 'initialized:\ncomponent: ' + cmp.description +
        '\nand library: ' + lib.version};
});

require(['framework'], function(framework) {
    alert(framework.init);
});

define('library', [], function() {
    return { version: '0.0.1' };
});

define('component', ['library'], function(lib) {
    return { description: 'uses library version: ' + lib.version };
});

As in all AMD loaders the order of dependencies does not matter.

Unlike all other loaders:

  1. Errors are not handled at all.
  2. Circular dependencies will silently fail.
  3. Short notation is not supported (name and dependencies arguments are required).
  4. Names are not normalized so relative paths (like ../../a) will not work.
  5. All dependencies must be listed in source code, they are not downloaded. Just like in almond.
  6. It will work only with modern browsers.

Comments

Lucas Meadows (@lmeadows)
Seems like good tradeoffs were made in this tiny AMD loader.
cancel

Revisions

  1. Initial version.