Last active
January 6, 2023 15:45
-
-
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
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
/** | |
* 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