AMD定义
AMD 定义了一套模块以及其依赖模块可被异步加载的API。然而这种机制洽洽改观了当前浏览器的规范的阻塞式加载模式,无疑能解决DOM文档加载时卡顿的现象。
API define(id?, dependencies?, factory);
规范中规定了一个define() function方法。
id[optional]:
模块的名字,如果未显示设置id,会被默认的设置为返回的脚本名字。id必须是一个 顶层或者绝对id ####
id的格式
- ‘/’分割的字符串
- 相对id, “.” 或者 “..”
- 不允许有后缀,如 “.js”
- 顶层(Top-Level)id用于解决模块概念上的根级命名空间
- 相对(Relative) id用于解决调用了”require”的模块id
例子:
- 模块"a/b/c"
请求 "../d"
, 则定位到 "a/d"
- 模块 "a/b/c"
请求 "./e"
, 则定位到 "a/b/e"
dependencies[optional]:
是当前定义的模块所依赖的module ids组成的数组, 依赖会优先于factory之前执行同时会以参数的形式传递给factory,数据index和参数顺序一一对应。
ids可以为relative ids,相对应于当前定义模块的相对路径。
规范中定义了3个特殊的依赖名,默认为空的dependency参数就会包含下面三个”全局变量”
- “require”
- “exports”
- “module”
factory[mandatory]:
是必须执行用于初始化本模块的函数。
如果factory参数是个object,那么这个对象必须被赋予 exported
如果factory函数有返回值(obj, function, or any value) 也必须被exported
Simplified CommonJS wrapping
如果dependencies参数被省略,module loader可能会选择扫描factory方法中的 require语句,前提条件是factory的第一个参数必须是require
require(“module-id”)
如果dependencies参数未被省略,module loader不会扫描factory内的require
Examples
require, exports使用
define("alpha", ["require", "exports", "beta"], function (require, exports, beta) {
exports.verb = function() {
return beta.verb();
//Or:
return require("beta").verb();
}
});
匿名模块定义
define(["alpha"], function(alpha){
return {
verb: function(){
return alpha.verb() + 2;
}
}
});
无依赖模块定义
define({
add: function(x, y){
return x + y;
}
});
Simplified CommonJS wrapping模块定义
define(function (require, exports, module) {
var a = require('a'),
b = require('b');
exports.action = function () {};
});
参考https://github.com/amdjs/amdjs-api/wiki/AMD
API require
require方法在AMD中实现了一个callback-based的调用,因为动态的计算依赖库可以使之异步的做加载。
Local vs Global require
define(['require'], function (require) {
//the require in here is a local require.
});
define(function (require, exports, module) {
//the require in here is a local require.
});
module id在这里是被当作top-level的绝对id
require(String)
define(function (require) {
var a = require('a');
});
require(Array, Function)
define(function (require) {
require(['a', 'b'], function (a, b) {
//modules a and b are now available for use.
});
});
require.toUrl(String)
把字符串转化为 [module id]+’.extension’的形式。
//cart.js contents:
define (function(require) {
//module ID part is './templates/a'
//'.extension is '.html'
//templatePath may end up to be something like
//'modules/cart/templates/a.html'
var templatePath = require.toUrl('./templates/a.html');
});