注意這裡使用Function來避免eval的可見域問題。
function loadModule(/*Module*/mod/*location*/, /*Function*/cb/*callback*/) {
var AJax = new XMLHttpRequest();
AJax.onreadystatechange = function(cb){
return function(){
if (this.readyState == 4 && this.status == 200) {
(new Function(this.responseText)).apply(window);
cb();
mod.loaded = true;
}
}
} (cb);
AJax.open('POST', mod.location, true);
AJax.send(null);
}
function loadModules (/*Array<Module>*/mods/*locations*/, /*Function*/cb/*callback*/) {
if (mods && mods.length <= 0) {
cb();
return;
}
var mod = mods.shift();
loadModule(mod, mods.length <= 0 ? cb : function() {
loadModules(mods, cb);
});
}
function LoadModules(/*Array<Module>*/mods, /*Function*/cb/*callback*/) {
var toLoad = [];
function ToLoad(mod) {
if (mod.loaded) return;
if (mod.reference instanceof Array) {
for (var i = 0; i < mod.reference.length; i ++) {
if (!(mod.reference[i].loading || mod.loaded)) {
ToLoad(mod.reference[i]);
}
}
}
toLoad.push(mod);
mod.loading = true;
}
for (var i = 0; i < mods.length; i++) {
ToLoad(mods[i]);
}
loadModules(toLoad, cb);
}