Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
on demand loading js
JsLoader = function(srcMap){
this.srcMap = {};
for(key in srcMap){
this.srcMap[key] = {state: "unload",src: srcMap[key],cb: []}
}
};
JsLoader.prototype = {
load: function(m,cb){
var that = this;
if(!this.srcMap[m]){
throw m + " was not found";
}
if(this.srcMap[m].state == "unload"){
var fjs = document.getElementsByTagName("script")[0]
var script = document.createElement("script");
this.srcMap[m].state = "loading"
that.srcMap[m].cb.push(cb);
script.onload = function(){
that.srcMap[m].state = "loaded"
while(that.srcMap[m].cb.length > 0){
that.srcMap[m].cb[0]();
that.srcMap[m].cb.shift()
}
}
script.onreadystatechange = function(){
if (script.readyState == "loaded" || script.readyState=="complete"){
that.srcMap[m].state = "loaded"
while(that.srcMap[m].cb.length > 0){
that.srcMap[m].cb[0]();
that.srcMap[m].cb.shift()
}
}
};
script.src = this.srcMap[m].src;
fjs.parentNode.insertBefore(script,fjs);
}else if(this.srcMap[m].state == "loading"){
this.srcMap[key].cb.push(cb);
}else{
cb()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.