Introduction to JavaScript AMD specifications (1)
AMD stands for "Asynchronous Module Definition", which means "Asynchronous Module Definition ". AMD defines that all modules we use are asynchronously loaded, so we need to put the code snippets of the dependent modules in a callback function, after the asynchronous loading module is complete (that is, when this module is available), the AMD library commonly used to trigger the callback function has require. js, sea. js click here for an AMD implementation of my own Sample Level
The AMD standard defines the following two APIs (1) require ([module], callback); (2) define ([depends], callback); The require interface is used to load a series of modules, the define interface is used to define and expose a module.
In AMD, our js Code is put in the require callback. The require function helps us load the dependent modules and the dependencies (dependency) of the processor) after all dependencies are loaded, use the module as the callback function parameter and call the callback function. in the following scenario, we need B and C modules for the js Code. module B does not depend on any module, and Module C depends on Module D.
require([B,C],function(B,C){ var A = {}; A.say = B.say; A.run = C.run; return A;});B.jsdefine([], function(){ var B = {}; B.say = function() { console.info('say hello!'); } return B;});C.jsdefine([D], function(D){ var C={}; c.run = function() { console.info(D.name + ' free running!'); } return C;})D.jsdefine([],function(){ var D={'name':'songzheng'}; return D;});
Assume that all modules are not loaded. The entire loading process is as follows (1) the Code depends on Module B and Module C and calls require to load Module B and Module C (2) module B does not rely on any modules. After loading successfully, callback factoryB and install Module B (3) when loading the C module, it is found that the C module depends on the D module and therefore calls require to load the D module (4). the D module does not depend on any module. After the load is successful, callback factoryD to load and install the D module (5) after the C-dependent D module is loaded successfully, call back factoryC, install C Module (6) After all dependencies are installed, run the callback function.
I added some log printing in my AMD implementation steps to better understand the module loading process.
<script type="text/javascript"> require(['Iris','cookie'], function(Iris, Cookie){ console.info(Iris); console.info(Cookie); });</script>