1.CommonJS, there is a global method, require (), for loading modules. Assuming that a mathematical module is math.js, it can be loaded as follows.
var math = require (' math ');
Then, you can invoke the method provided by the module:
var math = require (' math ');
Math.add (2,3); 5
The second line, Math.add (2, 3), runs after the first line of require (' math '), so it must wait until the math.js load is complete. That is, if the load time is long, the entire application will stop there and so on.
This is not a problem on the server side, because all the modules are stored on the local hard disk, can be loaded synchronously, waiting time is the hard disk read time. However, for the browser, this is a big problem, because the modules are placed on the server side, the waiting time depends on the speed of the network, it may take a long time, the browser is in "Suspended animation" status.
As a result, the browser-side module cannot be "synchronous-loaded" (synchronous) and can only take "asynchronous load" (asynchronous). This is the background to the birth of the AMD specification.
2:AMD is the abbreviation for "Asynchronous module definition", which means "asynchronous block definition". It loads the module asynchronously, and the module's load does not affect the execution of the statement behind it. All statements that rely on this module are defined in a callback function that will not run until the load is complete.
AMD also uses the Require () statement to load the module, but unlike COMMONJS, it requires two parameters:
Require ([module], callback);
The first parameter, [module], is an array in which the member is the module to be loaded, and the second parameter, callback, is the callback function after the load succeeds. If you rewrite the previous code in AMD form, this is the following:
Require ([' math '], function (math) {
Math.add (2, 3);
});
Math.add () is not synchronized with the math module, and the browser does not take place in animation. So it's clear that AMD is better suited for a browser environment.
Currently, there are two main JavaScript libraries that implement the AMD specification: Require.js and Curl.js. The third part of this series will introduce require.js to further explain AMD's usage and how to put modular programming into combat.
About AMD (asynchronous load Module) and cmd (synchronous loading module), Require.js