Asynchronous Module Definition (AMD) is the most popular module specification that implements asynchronous module loading. AMD is actually an early fork of CommonJS, and also uses the require and exports syntax.
Just as there are module bundlers for CommonJS modules, there are module loaders for AMD modules. These tools are called loaders because they load the modules from the client directly. The most popular module loader is Require.js. Require.js provides you with a define function, which you can use to define your module. You can pass in a list of dependencies as its first argument. Let's look at an example:
// greeter.js
define(function () {
function helloWorld(name) {
process.stdout.write(`hello ${name}!\n`)
};
return { sayHello: helloWorld }
});
// main.js
define(["./greeter.js"], function (greeter) {
// Only ran after the `greeter` module is loaded
greeter.sayHello("Daniel");
});
When the main module is initiated, it will first load the greeter module, and pass the object returned into the function that defines the main module. This ensures that modules are loaded in the correct order.
Require.js handles the loading of these modules in the background, parallelizing them if possible. This means downstream code execution is not blocked.