-
-
Save dziku86/1135f995f48145d3f36afb2d5628eea3 to your computer and use it in GitHub Desktop.
JS ScriptLoader using ES6 Promises
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 ScriptLoader () { | |
const loader = url => new Promise((resolve, reject) => { | |
const script = document.createElement('script') | |
script.src = url | |
script.async = !0 | |
script.addEventListener('load', resolve(script), !1) | |
script.addEventListener('error', reject(script), !1) | |
body.appendChild(script) | |
}) | |
this.load = url => loader(url) | |
} |
Author
dziku86
commented
Jan 1, 2021
Load script only once:
let scriptsloaded = ''
function ScriptLoader () {
if (criptsloaded.indexOf(`[${url}]`) === -1) {
const loader = url => new Promise((resolve, reject) => {
const script = document.createElement('script')
script.src = url
script.async = !0
script.addEventListener('load', resolve(script), !1)
script.addEventListener('error', reject(script), !1)
body.appendChild(script)
})
this.load = url => loader(url)
scriptsloaded += `[${url}]`
}
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment