異步加載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) 類型的加載過程當中。

不過,更重要的是不強制運行時服務器進程轉換代碼,不然容易致使調試困難,並且函數包裝器在注入服務器進程後就丟失行號信息。

相關文章
相關標籤/搜索