Consider this example from their website
define(function (require) {
var foo = require('foo');
//Define this module as exporting a function
return function () {
foo.doSomething();
};
});
My question is, as 'foo' is loaded asynchronously, how does the Javascript below it not execute before it has loaded?
This is explained in http://requirejs.org/docs/api.html#cjsmodule and http://requirejs.org/docs/whyamd.html#sugar.
Require.js will at some point (before running the function) look at the string representation of the function, find all require
calls to determine the dependencies and load them.
To make this easier, and to make it easy to do a simple wrapping around CommonJS modules, this form of define is supported, sometimes referred to as "simplified CommonJS wrapping":
define(function (require) { var dependency1 = require('dependency1'), dependency2 = require('dependency2'); return function () {}; });
The AMD loader will parse out the
require('')
calls by usingFunction.prototype.toString()
, then internally convert the above define call into this:define(['require', 'dependency1', 'dependency2'], function (require) { var dependency1 = require('dependency1'), dependency2 = require('dependency2'); return function () {}; });
This allows the loader to load
dependency1
anddependency2
asynchronously, execute those dependencies, then execute this function.