Skip to content

Instantly share code, notes, and snippets.

@BananaAcid
Created October 15, 2022 23:41
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/b4c867f859a67a4bf3f19183eb154db7 to your computer and use it in GitHub Desktop.
Save BananaAcid/b4c867f859a67a4bf3f19183eb154db7 to your computer and use it in GitHub Desktop.
loads a script/css/img/video and awaits
/**
* Nabil Redmann (BananaAcid), License MIT
*/
async function loadDependency(url, elementName, urlAttribute, attributes = {}, append = true) {
// check if it was added already
const prevElements = document.querySelectorAll(`${elementName}[${urlAttribute}="${url}"]`);
if (prevElements.length) return append ? true : prevElements[0];
// load if missing
let dep = document.createElement(elementName);
dep[urlAttribute] = url;
// add additional attribtues
Object.entries(attributes).forEach( ([k,v]) => dep[k] = v );
if (append) (document.head || document.body).appendChild(dep);
// wait for it to be loaded or failed.
let done = await new Promise( (resolve, reject) => {dep.onload = resolve; dep.onerror = reject;} )
.then(_=> append ? true : dep).catch(_=> false);
return done;
}
// usage examples
// just await
let luxonLoaded = await loadDependency('https://cdn.jsdelivr.net/npm/luxon@3.0.4/build/global/luxon.min.js', 'script', 'src', {id: 'rememberMe1'});
console.log('successful?', luxonLoaded);
// just async, Promise style
loadDependency('https://cdn.jsdelivr.net/npm/luxon@3.0.4/build/global/luxon.min.js', 'script', 'src', {id: 'rememberMe2'})
.then( result => console.log('successful?', result));
loadDependency('https://unpkg.com/open-props', 'link', 'href', {rel: 'stylesheet', id: 'rememberMe3'})
.then( result => console.log('successful?', result, getComputedStyle(document.documentElement).getPropertyValue('--blue-0')));
// multiple, Promise style
Promise.all([
loadDependency('https://cdn.jsdelivr.net/npm/luxon@3.0.4/build/global/luxon.min.js', 'script', 'src', {id: 'rememberMe4'}),
loadDependency('https://unpkg.com/open-props', 'link', 'href', {rel: 'stylesheet', id: 'rememberMe5'}),
])
.then( results => console.log('all loaded?', results));
// multiple await style
let mutliResults = await Promise.all([
loadDependency('https://cdn.jsdelivr.net/npm/luxon@3.0.4/build/global/luxon.min.js', 'script', 'src', {id: 'rememberMe4'}),
loadDependency('https://unpkg.com/open-props', 'link', 'href', {rel: 'stylesheet', id: 'rememberMe5'}),
]);
console.log('all loaded?', mutliResults);
// load image and get its element
loadDependency('https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png', 'img', 'src', {id: 'rememberMe2'}, append=false)
.then( result => console.log('successful?', result));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment