异步加载js(3)

1.6 head.appendChild()浏览器

为了实现脚本的按需加载,并避免阻塞页面渲染,能够使用 head.appendChild() 来服务器

在 <head> 部分添加 JavaScript 脚本,并且在页面加载完毕后再执行脚本。app

var head = document.getElementsByTagName('head')[0],函数

script = document.createElement('script');ui

script.src = url;this

head.appendChild(script);url

head.appendChild() 的不足在于用户仍然须要在执行代码前处理模块之间的依赖关prototype

系,而且在执行代码前提早加载依赖的模块。调试

1.7 Function Wrappingcode

为了在脚本执行前处理模块依赖关系并提早加载,用户须要使用函数包装器来构建

本身的模块加载 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) 类型的加载过程当中。

不过,更重要的是不强制运行时服务器进程转换代码,不然容易致使调试困难,并且函数包装器在注入服务器进程后就丢失行号信息。

相关文章
相关标签/搜索