I. modular specifications of js:
Server: commonjs
Browser end: AMD (abbreviation of "Asynchronous Module Definition", meaning "Asynchronous Module Definition ")
Ii. Why AMD
The following code
var math = require('math'); math.add(2, 3);
You must wait until the math. js loading is complete. Otherwise, the loading takes a long time.
Iii. define
Define (id ?, Dependencies ?, Factory );
Where:
- Id: module id, which can be omitted.
- Dependencies: the dependent module, which can be omitted.
- Factory: module implementation, or a JavaScript Object. The following is a simple three-tier structure (basic library, UI Layer, and application layer) developed using AMD: base. js
define(function() { return { mix: function(source, target) { } };});
Ui. jsdefine(['base'], function(base) { return { show: function() { // todo with module base } }});
Page. jsdefine(['data', 'ui'], function(data, ui) { // init here});
Data. jsdefine({ users: [], members: []});
The preceding three usage methods of define are also demonstrated,1. Define a module without dependency(Base. js)2. Define a depended Module(Ui. js, page. js)3. Define the Data Object Module(Data. js) you will find that the module is not displayed, that is, the module nameddefine('index', ['data','base'], function(data, base) { // todo});
The named module is not recommended most of the time. It is generally used when multiple modules are merged by the packaging tool into a js file. As mentioned above, the order of dependencies elements is one-to-one correspondence with factory, which is not very rigorous. AMD began to propose its own module style to get rid of CommonJS constraints. But later I made another compromise and was compatible with CommonJS Modules/Wrappings. That is, you can write it like this.define(function(require, exports, module) { var base = require('base'); exports.show = function() { // todo with module base } });
The format is the same as that of Node. js except for a function layer: Use require to obtain the dependency module and use exports to export the API.Iv. requireRequire ([module], callback );
The first parameter [module] is an array in which the member is the module to be loaded; the second parameter callback is the callback function after successful loading. If you rewrite the previous code to the AMD format, it is as follows:
require(['math'], function (math) { math.add(2, 3); });
Math. add () is not synchronized with the math module, and the browser will not be suspended. Obviously, AMD is suitable for browser environments.
Currently, there are two major Javascript libraries that implement AMD specifications: require. js and curl. js.