Skip to content

Instantly share code, notes, and snippets.

@abdullahoguk
Created February 25, 2021 06:52
Show Gist options
  • Save abdullahoguk/246c4179d14d0976dd903e2d1ff44e56 to your computer and use it in GitHub Desktop.
Save abdullahoguk/246c4179d14d0976dd903e2d1ff44e56 to your computer and use it in GitHub Desktop.
Load scripts dynamically in JS
//Source: https://aaronsmith.online/easily-load-an-external-script-using-javascript/
//-------------------PROMISE METHOD --------------------------
/**
* Loads a JavaScript file and returns a Promise for when it is loaded
*/
const loadScript = src => {
return new Promise((resolve, reject) => {
const script = document.createElement('script')
script.type = 'text/javascript'
script.onload = resolve
script.onerror = reject
script.src = src
document.head.append(script)
})
}
loadScript('https://code.jquery.com/jquery-3.4.1.min.js')
.then(() => loadScript('https://code.jquery.com/ui/1.12.1/jquery-ui.min.js'))
.then(() => {
// now safe to use jQuery and jQuery UI, which depends on jQuery
})
.catch(() => console.error('Something went wrong.'))
//-------------------CALLBACK METHOD --------------------------
/**
* Plays well with historic artifacts
*/
function loadScript(src, callback) {
var script = document.createElement('script')
script.type = 'text/javascript'
// IE
if (script.readyState) {
script.onreadystatechange = function () {
if (script.readyState === 'loaded' || script.readyState === 'complete') {
script.onreadystatechange = null
callback()
}
}
}
// Others
else {
script.onload = callback
}
script.src = src
document.head.appendChild(script)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment