
92
|
第六章
會處於被鎖住無法使用的狀態;第二,我們會需要透過 eval 相關函式來執行 script 程式
(這是種很糟糕的程式寫法,建議能免則免)。有鑑於此,CommonJS 的開發團隊制定
了一套模組傳輸格式(module transport format)(
http://wiki.commonjs.org/wiki/Modules/
Transport
)。模組傳輸格式會將 CommonJS 模組包裝成一組回叫函式,好讓用戶端能以
非同步的方式來載入 CommonJS 模組。
再回頭來看前一段範例程式碼,只要用模組傳輸格式把它包裝一下,就能讓瀏覽器以非
同步方式載入模組:
// maths.js
require.define("maths", function(require, exports){
exports.per = function(value, total) {
return( (value / total) * 100 );
};
});
// application.js
require.define("application", function(require, exports){
var per = require("./maths").per;
assertEqual( per(50, 100), 50 );
}, ["./maths"]); // 列出相依檔案(maths.js)
用模組傳輸格式包裝過後,就能透過模組載入器函式庫(module loader library ...