Skip to content

Commit adeef6e

Browse files
ion1aklinker1
andauthored
fix: Make injectScript wait until script is actually loaded (#1763)
Co-authored-by: Aaron <[email protected]>
1 parent 6f84d45 commit adeef6e

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

packages/wxt/src/utils/inject-script.ts

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,13 +32,39 @@ export async function injectScript(
3232
script.src = url;
3333
}
3434

35+
const loadedPromise = makeLoadedPromise(script);
36+
3537
await options?.modifyScript?.(script);
3638

3739
(document.head ?? document.documentElement).append(script);
3840

3941
if (!options?.keepInDom) {
4042
script.remove();
4143
}
44+
45+
await loadedPromise;
46+
}
47+
48+
function makeLoadedPromise(script: HTMLScriptElement): Promise<void> {
49+
return new Promise((resolve, reject) => {
50+
const onload = () => {
51+
resolve();
52+
cleanup();
53+
};
54+
55+
const onerror = () => {
56+
reject(new Error(`Failed to load script: ${script.src}`));
57+
cleanup();
58+
};
59+
60+
const cleanup = () => {
61+
script.removeEventListener('load', onload);
62+
script.removeEventListener('error', onerror);
63+
};
64+
65+
script.addEventListener('load', onload);
66+
script.addEventListener('error', onerror);
67+
});
4268
}
4369

4470
export interface InjectScriptOptions {

0 commit comments

Comments
 (0)