forked from clerk/javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathloadScript.ts
More file actions
60 lines (49 loc) · 1.5 KB
/
Copy pathloadScript.ts
File metadata and controls
60 lines (49 loc) · 1.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import { retry } from './retry';
const NO_DOCUMENT_ERROR = 'loadScript cannot be called when document does not exist';
const NO_SRC_ERROR = 'loadScript cannot be called without a src';
type LoadScriptOptions = {
async?: boolean;
defer?: boolean;
crossOrigin?: 'anonymous' | 'use-credentials';
nonce?: string;
beforeLoad?: (script: HTMLScriptElement) => void;
};
/**
*
*/
export async function loadScript(src = '', opts: LoadScriptOptions): Promise<HTMLScriptElement> {
const { async, defer, beforeLoad, crossOrigin, nonce } = opts || {};
const load = () => {
return new Promise<HTMLScriptElement>((resolve, reject) => {
if (!src) {
reject(new Error(NO_SRC_ERROR));
}
if (!document || !document.body) {
reject(new Error(NO_DOCUMENT_ERROR));
}
const script = document.createElement('script');
if (crossOrigin) {
script.setAttribute('crossorigin', crossOrigin);
}
script.async = async || false;
script.defer = defer || false;
script.addEventListener('load', () => {
script.remove();
resolve(script);
});
script.addEventListener('error', event => {
script.remove();
reject(event.error ?? new Error(`failed to load script: ${src}`));
});
script.src = src;
script.nonce = nonce;
beforeLoad?.(script);
document.body.appendChild(script);
});
};
return retry(load, {
shouldRetry: (_, iterations) => {
return iterations <= 5;
},
});
}