ndf-elements
Version:
My collection of useful custom elements.
60 lines (52 loc) • 1.53 kB
JavaScript
/**
* Wait for Javascripts linked to from external CDNs to load.
*
* @copyright © Nick Freear, 23-Jan-2022.
*/
export async function leafletViaCdn () {
const Leaflet = await whenTimeout(() => window.L, 'Rainbow');
console.debug('Leaflet - CDN:', Leaflet);
return Leaflet;
}
// Used in: MyCode, MyBookmarklet.
export async function rainbowViaCdn () {
const Rainbow = await whenTimeout(() => window.Rainbow, 'Rainbow');
console.debug('Rainbow - CDN:', Rainbow);
return Rainbow;
}
// Used in: BookmarkletScript.
export async function terserViaCdn () {
const Terser = await whenTimeout(() => window.Terser, 'Terser');
console.debug('Terser - CDN:', Terser);
return Terser;
}
/**
* When a time-dependent condition is met, resolve a promise.
* If a timeout expires - reject the promise.
*
* @see https://gist.github.com/nfreear/f40470e1aec63f442a8a
* @see https://github.com/nfreear/whendo.git
*/
export function whenTimeout (testCallbackFn, id = null, timeoutMs = 6000, intervalMs = 150) {
return new Promise((resolve, reject) => {
const TID = {};
TID.interval = setInterval(() => {
const RESULT = testCallbackFn();
if (RESULT) {
clearAll();
resolve(RESULT);
}
},
intervalMs);
TID.timeout = setTimeout(() => {
clearAll();
reject(new Error(`whenTimeout expired: ${id}`));
},
timeoutMs);
function clearAll () {
// const clearAll=()=>{
clearInterval(TID.interval);
clearTimeout(TID.timeout);
}
});
}