-
Notifications
You must be signed in to change notification settings - Fork 0
/
tinyAMD.js
97 lines (80 loc) · 3.11 KB
/
tinyAMD.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
window.tinyAMD = (function() {
this._loadScript = function(src,callback){
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
try {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
return;
}
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
callback(xmlhttp);
}
};
xmlhttp.script_src = src;
xmlhttp.open("GET", src , true);
xmlhttp.send();
};
this._exec = function(parent,path,string) {
var newModule = new Function('return ' + string)();
newModule.parent = parent;
newModule.name = path;
if(!newModule.depPaths.length && newModule.parent){
newModule.parent.addModuleResult(newModule);
}
return newModule;
};
this._defineShim = function(shimLib,callback){
self._loadScript(shimLib.paths,function(xmlhttp){
eval('(function() {' + xmlhttp.responseText + '}())');
callback(window[shimLib.exports]);
});
};
window.define = function(scripts, complete) {
var module = new tinyAMD.module(scripts,complete);
module.loadDeps();
return module;
};
return{
shim :{},
module:function(scripts, callback){
this.args = [];
this.depPaths = scripts;
this.depsLoaded = [];
this.callback = callback;
this.execute = function(){
if(this.parent){
this.parent.addModuleResult(this);
}else{
return this.callback.apply(this, this.args);
}
};
this.addModuleResult = function(module){
this.args[this.depPaths.indexOf(module.name)] = module.callback.apply(module, module.args);
this.depsLoaded.push(module.name);
if(this.depsLoaded.length == this.depPaths.length)
this.execute();
};
this.loadDeps = function(){
this.depPaths.forEach(function(dep,index){
if(tinyAMD.shim[dep]){
self._defineShim(tinyAMD.shim[dep],function(){
this.depsLoaded.push(tinyAMD.shim[dep].exports);
this.args[this.depPaths.indexOf(dep)] = window[tinyAMD.shim[dep].exports];
if(this.args.length == this.depsLoaded.length)
this.execute();
}.bind(this));
}else{
self._loadScript(dep,function(xmlhttp){
self._exec(this, xmlhttp.script_src,xmlhttp.responseText);
}.bind(this));
}
}.bind(this));
};
}
};
})();