Last active
January 3, 2023 14:36
-
-
Save marcus-at-localhost/da0cc3da4bfa70399963a4bd32b9e5bf to your computer and use it in GitHub Desktop.
[Load Script] load javascript library with promise in runtime and check if script already exists #es6 #promise
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
// added check if script is loaded | |
// @link https://stackoverflow.com/a/49780469/814031 | |
// usage: | |
/* | |
let script = loadScript('https://cdn.jsdelivr.net/combine/npm/leaflet@1.5.1,npm/togpx@0.5.4/togpx.min.js'); | |
script.then( function (){ | |
L.map('map') | |
}); | |
*/ | |
const loadScript = (source, beforeEl, async = true, defer = true) => { | |
return new Promise((resolve, reject) => { | |
var scriptIsLoaded = document.querySelectorAll("script[src='" + source + "']").length > 0; | |
if (scriptIsLoaded) { | |
return resolve(); | |
} | |
let script = document.createElement('script'); | |
const prior = beforeEl || document.getElementsByTagName('script')[0]; | |
script.async = async; | |
script.defer = defer; | |
function onloadHander(_, isAbort) { | |
if (isAbort || !script.readyState || /loaded|complete/.test(script.readyState)) { | |
script.onload = null; | |
script.onreadystatechange = null; | |
script = undefined; | |
if (isAbort) { reject(); } else { resolve(); } | |
} | |
} | |
script.onload = onloadHander; | |
script.onreadystatechange = onloadHander; | |
script.src = source; | |
prior.parentNode.insertBefore(script, prior); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Awesome. Helped me in a Rails app with Turbo when using Bootstrap from a CDN.