Created
January 1, 2015 03:58
-
-
Save takeshy/eebc46dca9d3d5f37d9b to your computer and use it in GitHub Desktop.
on demand loading js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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