Skip to content

Instantly share code, notes, and snippets.

@bradberger
Created July 30, 2014 07:33
Show Gist options
  • Save bradberger/9d3ba85c63c21b317f5d to your computer and use it in GitHub Desktop.
Save bradberger/9d3ba85c63c21b317f5d to your computer and use it in GitHub Desktop.
Promise-based JS script loader
function script(url) {
if(Array.isArray(url)) {
var self = this, prom = [];
url.forEach(function(item) {
prom.push(self.script(item));
});
return Promise.all(prom);
}
return new Promise(function (resolve, reject) {
var r = false,
t = document.getElementsByTagName("script")[0],
s = document.createElement("script");
s.type = "text/javascript";
s.src = url;
s.async = true;
s.onload = s.onreadystatechange = function () {
if (!r && (!this.readyState || this.readyState == "complete")) {
r = true;
resolve(this);
}
};
s.onerror = s.onabort = reject;
t.parentNode.insertBefore(s, t);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment