Skip to content

Instantly share code, notes, and snippets.

@googlicius
Last active October 9, 2018 06:04
Show Gist options
  • Save googlicius/941be5aff4912174b79896a2cbd8e9e9 to your computer and use it in GitHub Desktop.
Save googlicius/941be5aff4912174b79896a2cbd8e9e9 to your computer and use it in GitHub Desktop.
/**
* Load JS file async
*
* @param url url of JS file
* @param cb Callback after file has loaded.
* @param wait_id id of element that being waited to load.
* @returns Promise<any>
*/
export const loadAsyncJS = (url: string | Array<string>, cb?: (error?: any) => void, wait_src: string = null): Promise<any> => {
const createElement = (d, s, url) => {
var js = d.createElement(s);
js.src = url;
return js;
}
var promiseAll: Promise<any>;
const run = () => {
var fjs = document.getElementsByTagName('script')[0];
var promises: Array<Promise<any>> = [];
if (typeof url == 'string') {
url = [url];
}
url.forEach((url_str, i) => {
if(!document.querySelector(`[src="${url_str}"]`)) {
var js = createElement(document, 'script', url_str);
fjs.parentNode.insertBefore(js, fjs);
var promise = new Promise((resolve, reject) => {
js.onload = () => {
js.setAttribute("data-loaded", "true");
resolve();
};
});
promises.push(promise);
}
});
promiseAll = Promise.all(promises);
if(cb) {
promiseAll.then(() => cb(), err => cb(err));
}
}
var wait_el = document.querySelector(wait_src);
if (wait_el && !wait_el.getAttribute("data-loaded")) {
addOnloadHandler(wait_el, () => run());
} else {
run();
}
return promiseAll;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment