Skip to content

Instantly share code, notes, and snippets.

@gkatsev
Created May 10, 2013 23:48
Show Gist options
  • Save gkatsev/5558287 to your computer and use it in GitHub Desktop.
Save gkatsev/5558287 to your computer and use it in GitHub Desktop.
A simple script loader
// loadScript :: String, function, predicate [, arg1 [, arg2 [, ...]]] -> undefined
// The optional arguments will get passed to the callback
var loadScript = (function() {
var scripts = {};
return function(url, callback, predicate) {
var
body = document.body,
script = document.createElement('script'),
loaded = false,
optionalArgs = [].slice.call(arguments, 3);
if (predicate || scripts[url]) {
callback.apply(null, optionalArgs);
} else {
script.onload = script.onreadystatechange = function() {
if (!loaded && (!this.readyState || this.readyState === 'loaded' || this.readyState === 'complete')) {
loaded = true;
script.onload = script.onreadystatechange = null;
scripts[url] = 1;
callback.apply(null, optionalArgs);
}
};
script.src = url;
body.appendChild(script);
}
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment