Load Script Promise
by gavinfoley
JavaScript
async function ScriptLoader(src, global) {
this.src = src;
this.global = global;
this.protocol = document.location.protocol;
function loadScript() {
return new Promise((resolve, reject) => {
// Create script element and set attributes
const script = document.createElement('script');
script.type = 'text/javascript';
script.async = true;
script.src = `${this.protocol}//${this.src}`;
// Append the script to the DOM
const el = document.getElementsByTagName('script')[0];
el.parentNode.insertBefore(script, el);
// Resolve the promise once the script is loaded
script.addEventListener('load', () => {
resolve(script);
});
// Catch any errors while loading the script
script.addEventListener('error', () => {
reject(new Error(`${this.src} failed to load.`));
});
});
}
return new Promise(async (resolve, reject) => {
if (window[this.global]) {
console.info(`'${this.global}' is already loaded.`);
resolve(window[this.global]);
return;
}
try {
await loadScript();
resolve(window[this.global]);
} catch (e) {
reject(e);
}
});
}
(async () => {
var google = await ScriptLoader("maps.google.com/maps/api/js?v=3&sensor=false", "google");
console.log("Google loaded", google);
google = await ScriptLoader("maps.google.com/maps/api/js?v=3&sensor=false", "google");
})();