Skip to content

Instantly share code, notes, and snippets.

@BananaAcid
Last active January 6, 2023 15:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BananaAcid/1951ef38889712c59cc102640f37ec27 to your computer and use it in GitHub Desktop.
Save BananaAcid/1951ef38889712c59cc102640f37ec27 to your computer and use it in GitHub Desktop.
laod a script and await until it is loaded, superseeded by loadDependency.await.js
/**
* Nabil Redmann (BananaAcid), License MIT
*/
async function loadScript(url) {
// check if it was added already
if (document.querySelectorAll(`script[src="${url}"]`).length) return true;
// load if missing
let script = document.createElement('script');
script.src = url;
(document.head || document.body).appendChild(script);
// wait for it to be loaded or failed.
let done = await new Promise( (resolve, reject) => {script.onload = resolve; script.onerror = reject;} )
.then(_=> true).catch(_=> false);
return done;
}
let getTime = async _ => {
let done = await loadScript('https://cdn.jsdelivr.net/npm/luxon@3.0.4/build/global/luxon.min.js');
if (done)
console.log('added script, global is now available', window.luxon);
else
console.error('could not add script');
// use if available
if (window.luxon) {
let time = window.luxon.DateTime.now()/*.setZone('Europe/Berlin') or current by default*/.toISO();
console.log('time-iso', time);
}
}
// trigger
getTime();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment