-
-
Save AmesianX/a16c03206753fd194dbbbba5ad9f3721 to your computer and use it in GitHub Desktop.
A quick implementation of AMD
This file contains hidden or 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
(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