1.6 head.appendChild()
为了实现脚本的按需加载,并避免阻塞页面渲染,可以使用 head.appendChild() 来
在 <head> 部分添加 JavaScript 脚本,而且在页面加载完毕后再执行脚本。
var head = document.getElementsByTagName('head')[0],
script = document.createElement('script');
script.src = url;
head.appendChild(script);
head.appendChild() 的不足在于用户仍然需要在执行代码前处理模块之间的依赖关
系,并且在执行代码前提前加载依赖的模块。
1.7 Function Wrapping
为了在脚本执行前处理模块依赖关系并提前加载,用户需要使用函数包装器来构建
自己的模块加载 API。
define(
// The name of this module
"types/Manager",
// The array of dependencies
["types/Employee"],
// The function to execute when all dependencies
// when all dependencies have loaded.
// The arguments to this function are the array of
// dependencies mentioned above.
function (Employee){
function Manager(){
this.reports = [];
}
// This will now work
Manager.prototype = new Employee();
// return the Manager constructor function
// so it can be used by other modules.
return Manager;
}
);
上面是 RequireJS 使用的语法,而且还可以进一步简化来加载原始的 JavaScript 文件,而且无需定义模块。
require(["some/script.js"], function(){
// This function is called after some/script.js had loaded.
});
可以看到,函数包装器的语法更简洁,而且允许加载器进行 head.appendChile(script)的加载操作。
普通的 CommonJS 语法和函数包装器的语法不同,虽然它们都可以在浏览器中良好工作。
如果服务器进程可以将函数包装器转换为适合传输的模式,那么 CommonJS 语法也可以被用到 head.appendChild(script) 类型的加载过程中。
不过,更重要的是不强制运行时服务器进程转换代码,否则容易导致调试困难,而且函数包装器在注入服务器进程后就丢失行号信息。