Skip to content

Instantly share code, notes, and snippets.

@Gustavo6046 Gustavo6046/mloader.js
Last active Oct 13, 2018

Embed
What would you like to do?
JavaScript Bilateral Module Loader (JS-BML) – the core of CrossCore (pun not intended)!
var AjaxRequest = null;
if ((typeof require) === 'undefined') {
if ((typeof XMLHttpRequest) !== 'undefined')
AjaxRequest = function () {
return new XMLHttpRequest();
};
else if ((typeof ActiveXObject) !== 'undefined')
AjaxRequest = function () {
return new ActiveXObject("Microsoft.XMLHTTP");
};
else
throw new Error('The CrossCore bilateral module loader needs an AJAX-capable JavaScript API on your browser, but neither XMLHttpRequest, nor ActiveXObject, were found. Try using a newer browser.');
}
var loader = {
cache: {},
root: ".",
setRoot: function setRoot(root) {
if ((typeof require) !== 'undefined')
loader.root = root;
},
importModule: function importModule(modulePath, moduleName, callback, force) {
if (Object.keys(loader.cache).indexOf(moduleName) > -1 && !force)
callback(loader.cache[moduleName]);
if ((typeof require) === 'undefined') {
let req = new AjaxRequest();
req.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var mod = new Function("loader", this.responseText)(loader);
loader.cache[moduleName] = mod;
callback(mod);
}
};
req.open("GET", modulePath, true);
req.send();
} else {
var mod = new Function("loader", require('fs').readFileSync(require('path').join(loader.root, modulePath)))(loader);
loader.cache[moduleName] = mod;
callback(mod);
}
},
importModuleSync: function importModule(modulePath, moduleName, force) {
if (Object.keys(loader.cache).indexOf(moduleName) > -1 && !force)
return loader.cache[moduleName];
var mod;
if ((typeof require) === 'undefined') {
let req = new XMLHttpRequest();
req.open("GET", modulePath, false);
req.send();
if (req.status == 200) {
mod = new Function("loader", req.responseText)(loader);
loader.cache[moduleName] = mod;
return mod;
}
else
return null;
} else {
mod = new Function("loader", require('fs').readFileSync(require('path').join(loader.root, modulePath)))(loader);
loader.cache[moduleName] = mod;
return mod;
}
},
globalImport: function globalImport(modulePath, moduleName, force) {
function callback(mod) {
if ((typeof require) === 'undefined')
window[moduleName] = mod;
else
global[moduleName] = mod;
}
importModule(modulePath, moduleName, callback, force);
},
globalImportSync: function globalImportSync(modulePath, moduleName, force) {
function callback(mod) {
if ((typeof require) === 'undefined')
window[moduleName] = mod;
else
global[moduleName] = mod;
}
callback(importModuleSync(modulePath, moduleName, force));
},
};
if ((typeof require) !== 'undefined') {
require.modules = {};
module.exports = loader;
} else
window.loader = loader;
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.