Why Modular programming
If JS can also be like Python,java using import, the introduction of the module we want, what module we want to load what module, can give the front-end programming to bring more convenient, more clear structure. However, there is a premise that you must write the module in the same way.
Currently, there are two types of JavaScript module specifications: Commonjs and AMD.
CommonJS
In 2009, US programmer Ryan Dahl created the node. JS project, which uses the JavaScript language for server-side programming, marking the formal birth of JavaScript modular programming. In the browser environment, no module is not particularly big problem, after all, the complexity of the Web-page program is limited, but on the server side, must have the module, and the operating system and other applications to interact with, otherwise there is no programming. Node. JS's module system is implemented with reference to the COMMONJS specification. In Commonjs, there is a global method require () that is used to load the module.
var math = require (' math '); Math.add (// 5
However, due to a significant limitation, the COMMONJS specification does not apply to the browser environment. Runs after the first line require (' math '), so the math.js load must be completed. 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.
Amd
AMD is the abbreviation for "Asynchronous module definition", meaning "async module 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:
function (math) {Math.add (2, 3);});
We often hear of a JavaScript library: Require.js, which implements the AMD specification, which we can conveniently use for modular management.
Modular Programming Amd&commonjs