Created
November 1, 2017 20:43
-
-
Save srittau/ba0ec13f816a6a42d89d9c8712a7c0c5 to your computer and use it in GitHub Desktop.
Loading Modules in JavaScript v2
This file contains 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
// $Revision: 5816 $ | |
var include; | |
if (!include) { include = {}; } | |
include.base = "."; | |
include.ModuleLoader = function ModuleLoader() { | |
this.loadingModules = {}; | |
this.loadedModules = {}; | |
}; | |
include.ModuleLoader.prototype.loadModule = function(module, cb) { | |
if (this.loadedModules[module]) { | |
cb(); | |
return; | |
} | |
if (!this.loadingModules[module]) { | |
this.loadingModules[module] = []; | |
this.addScriptTag(module); | |
} | |
if (cb) { | |
this.loadingModules[module].push(cb); | |
} | |
}; | |
include.ModuleLoader.prototype.addScriptTag = function(module) { | |
var scriptTag = document.createElement("script"); | |
scriptTag.setAttribute("lang", "javascript"); | |
scriptTag.setAttribute("type", "application/javascript"); | |
scriptTag.setAttribute("src", this.moduleNameToFilename(module)); | |
scriptTag.onerror = function() { throw("could not load module " + module); } | |
document.getElementsByTagName("head")[0].appendChild(scriptTag); | |
}; | |
include.ModuleLoader.prototype.moduleNameToFilename = function(module) { | |
var prefix = include.base == "/" ? "/" : include.base + "/"; | |
return prefix + module.replace(/\./g, "/") + ".js"; | |
}; | |
include.ModuleLoader.prototype.moduleLoaded = function(module) { | |
this.loadedModules[module] = true; | |
for (var i = 0; i < this.loadingModules[module].length; i++) { | |
this.loadingModules[module][i](); | |
} | |
delete this.loadingModules[module]; | |
}; | |
include.loader = new include.ModuleLoader(); | |
include.module = function(module, cb) { | |
include.loader.loadModule(module, cb); | |
}; | |
include.moduleLoaded = function(module) { | |
include.loader.moduleLoaded(module); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment