Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
[Load Script] load javascript library with promise in runtime and check if script already exists #ES6 #promise
// 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
You can’t perform that action at this time.