Created
July 11, 2013 09:27
-
-
Save uupaa/5973973 to your computer and use it in GitHub Desktop.
Script loader
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
/* | |
Script("hoge.js", "huga.js", function(err, args) { | |
err || console.log("script loaded"); | |
}); | |
*/ | |
(function(global) { | |
var _loaded = {}; // { source: boolean, ... } | |
function Script(var_args) { // @var_args: (path, path, ... callback?) | |
var args = arguments; | |
var i = 0, iz = args.length; | |
var callback = null; | |
// detect callback | |
if (typeof args[iz - 1] === "function") { | |
callback = args[iz - 1]; | |
--iz; | |
} | |
var flow = new Flow(iz, callback); | |
for (; i < iz; ++i) { | |
load(args[i], flow); | |
} | |
} | |
function load(src, flow) { | |
if (src in _loaded) { | |
flow.pass(); // already loaded | |
} else { | |
var script = document.createElement("script"); | |
script.onerror = function(event) { | |
alert("Script load failed: " + src); | |
flow.miss(src); | |
}; | |
script.onload = function() { | |
_loaded[src] = true; | |
flow.pass(); | |
}; | |
script.src = src; | |
(document.head || document.body).appendChild(script); | |
} | |
} | |
global.Script = Script; | |
})(this); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment