Skip to content
This repository has been archived by the owner on May 8, 2024. It is now read-only.

Commit

Permalink
fix: loadScript race condition
Browse files Browse the repository at this point in the history
  • Loading branch information
luwes committed Jul 3, 2022
1 parent 6cd4448 commit eb5fa42
Showing 1 changed file with 12 additions and 5 deletions.
17 changes: 12 additions & 5 deletions src/utils.js
@@ -1,16 +1,23 @@
export async function loadScript(src, globalName) {
const loadScriptCache = {};
export async function loadScript(src, globalName, readyFnName) {
if (loadScriptCache[src]) return loadScriptCache[src];
if (globalName && self[globalName]) {
await delay(0);
return self[globalName];
}
return new Promise(function (resolve, reject) {
return (loadScriptCache[src] = new Promise(function (resolve, reject) {
const script = document.createElement('script');
script.src = src;
script.onload = () => resolve(self[globalName]);
const ready = () => resolve(self[globalName]);
if (readyFnName) (self[readyFnName] = ready);
script.onload = () => !readyFnName && ready();
script.onerror = reject;
document.head.appendChild(script);
});
document.head.append(script);
}));
}

export const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

export function promisify(fn) {
return (...args) =>
new Promise((resolve) => {
Expand Down

0 comments on commit eb5fa42

Please sign in to comment.