Skip to content

Instantly share code, notes, and snippets.

@AmesianX
Forked from corycook/amd.js
Created March 19, 2019 20:40
Show Gist options
  • Save AmesianX/a16c03206753fd194dbbbba5ad9f3721 to your computer and use it in GitHub Desktop.
Save AmesianX/a16c03206753fd194dbbbba5ad9f3721 to your computer and use it in GitHub Desktop.
A quick implementation of AMD
(function () {
var filename = "amd.js";
var scripts = Array.prototype.slice.call(document.querySelectorAll("script[src]"));
var self = scripts.filter(function (x) { return x.getAttribute("src").indexOf(filename) > -1; })[0];
var src = self.getAttribute("src");
var root = src.substring(0, src.indexOf(filename));
var modules = {};
this.define = function (def) {
var src = document.currentScript.getAttribute("src");
modules[src] = def;
};
function loading(state, done) {
state.count--;
if (state.count == 0) done();
}
this.require = function (sources, callback) {
function done() {
var m = sources.map(function (x) { return modules[root + x + ".js"](); });
callback.apply(this, m);
}
var unloaded = sources.filter(function (x) {
return !(x in modules);
});
var state = { count: unloaded.length };
unloaded.forEach(function (x) {
var script = document.createElement("script");
script.onload = loading.bind(script, state, done);
script.src = root + x + ".js";
document.head.appendChild(script);
});
if (state.count == 0) done();
};
}).call(this);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment