Created
July 30, 2014 07:33
-
-
Save bradberger/9d3ba85c63c21b317f5d to your computer and use it in GitHub Desktop.
Promise-based JS 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
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