var Loader = function () {
}
Loader.prototype = {
require: function (scripts, callback) {
this.loadCount = 0;
this.totalRequired = scripts.length;
this.callback = callback;
for (var i = 0; i < scripts.length; i++) {
this.writeScript(scripts[i]);
}
},
loaded: function (evt) {
this.loadCount++;
if (this.loadCount == this.totalRequired && typeof this.callback == 'function') this.callback.call();
},
writeScript: function (src) {
var self = this;
var s = document.createElement('script');
s.type = "text/javascript";
s.async = true;
s.src = src;
s.addEventListener('load', function (e) { self.loaded(e); }, false);
var head = document.getElementsByTagName('head')[0];
head.appendChild(s);
}
}
function loadScript(src,_timeout) {
return new Promise(function(resolve, reject){
if(!src){
reject(new TypeError("filename is missing"));
return;
}
var script=document.createElement("script"),
timer,
head=document.getElementsByTagName("head")[0];
function leanup(){
clearTimeout(timer);
timer=null;
script.onerror=script.onreadystatechange=script.onload=null;
}
function onload(){
leanup();
if(!script.onreadystatechange||(script.readyState&&script.readyState=="complete")){
resolve(script);
}
}
script.onerror=function(error){
leanup();
head.removeChild(script);
script=null;
reject(new Error("network"));
};
if (script.onreadystatechange === undefined) {
script.onload = onload;
} else {
script.onreadystatechange = onload;
}
timer=setTimeout(script.onerror,_timeout||30000);
script.setAttribute("type", "text/javascript");
script.setAttribute("src", src);
head.appendChild(script);
});
}
loadScript("script.js").then(function(script){
console.log("ok",script);
},function(error){
console.warn("fail");
});