Skip to content

Instantly share code, notes, and snippets.

@bigeyex
Created August 1, 2014 21:05
Show Gist options
  • Save bigeyex/efe6cad64aa8e1c288b6 to your computer and use it in GitHub Desktop.
Save bigeyex/efe6cad64aa8e1c288b6 to your computer and use it in GitHub Desktop.
manage javascript dependancies
/*
JSRequire module
by: wangyu (bigeyex@gmail.com)
manage javascript dependancies.
usage:
jsrequire(['one.js', 'two.js'], function(){
// code after one.js and two.js loaded...
});
*/
function JSRequire(base_path){
this.scriptList = {};
this.waitingList = [];
this.waitingCallbacks = [];
this.basePath = base_path?base_path:'';
var self = this;
window.jsrequire = function(scripts, callback){
var needLoad = false;
for(var i in scripts){
if(!(scripts[i] in self.scriptList)){
needLoad = true;
self.waitingList.push(scripts[i]);
}
}
if(needLoad){
self.waitingCallbacks.push(callback);
self.loadScript();
}
else{
callback();
}
};
this.loadScript = function(){
var oneScript = self.waitingList.pop();
if(oneScript){
var head= document.getElementsByTagName('head')[0];
var script= document.createElement('script');
script.type= 'text/javascript';
script.onreadystatechange= function () {
if (this.readyState == 'loaded' || this.readyState == 'complete') self.scriptLoaded();
}
script.onload= self.scriptLoaded;
script.src= self.basePath+oneScript;
head.appendChild(script);
}
};
this.scriptLoaded = function(){
if(self.waitingList.length > 0){
self.loadScript();
}
else{
for(var i in self.waitingCallbacks){
self.waitingCallbacks[i]();
}
}
};
}
new JSRequire(app_path+'/Public/js/');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment