Skip to content

Instantly share code, notes, and snippets.

@dziku86
Forked from itsjavi/scriptloader.js
Last active February 20, 2021 21:57
Show Gist options
  • Save dziku86/1135f995f48145d3f36afb2d5628eea3 to your computer and use it in GitHub Desktop.
Save dziku86/1135f995f48145d3f36afb2d5628eea3 to your computer and use it in GitHub Desktop.
JS ScriptLoader using ES6 Promises
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)
}
@dziku86
Copy link
Author

dziku86 commented Jan 1, 2021

const loginBtn = document.querySelector('h1')
loginBtn.addEventListener('click', () => {
  const loader = new ScriptLoader()
  loader.load([
    'slider.js'
  ]).then(() => console.log('loaded!'))
})

@dziku86
Copy link
Author

dziku86 commented Feb 20, 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