Skip to content

Instantly share code, notes, and snippets.

@srittau
Created Nov 1, 2017
Embed
What would you like to do?
Loading Modules in JavaScript v2
// $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