Open hytzgroup opened 4 years ago
(function(global){
var defineModels = {};
function loadScript(url,callback){
var $body = document.body || document.getElementsByTagName('body')[0];
var $script = document.createElement('script');
$script.async = true;
$script.src = './'+url+'.js';
$script.onload = function(event){
callback(event);
}
$body.appendChild($script);
}
function load(id,callback){
loadScript(id,function scriptFn(){
// b model
var model = getModel(id);
// load b model deps e
req(model.deps,function reqFn2(param){
callback(model.callback(param));
});
});
}
function getModel(id){
return defineModels[id];
}
// 职责链模式递归循环
function req(deps,callback){
var params = [];
if(!deps.length){
return callback();
}
var total = deps.length;
for(var i = 0, len = deps.length; i < len; i++){
(function(index){
// load b.js
load(deps[index],function loadFn(param){
--total;
params.push(param);
if(total == 0){
callback.apply(null,params);
}
});
})(i);
}
}
// 模块
function define(id,deps,callback){
defineModels[id] = {
loaded:false,
deps:deps,
callback:callback
}
}
global.require = req;
global.define = define;
})(window);
req(['b'],reqFn)
load('b',function loadFn(){
callback = reqFn;
})
loadScript('b',function scriptFn(){
// 成功加载 model b
req(['e'],function reqFn2(){
callback = loadFn;
});
});
load('e',function loadFn(){
callback = reqFn2;
});
loadScript('b',function scriptFn(){
// 成功加载 model e
req([],function reqFn2(){
callback = loadFn;
});
});
reqFn2();