-
Notifications
You must be signed in to change notification settings - Fork 168
Expand file tree
/
Copy pathScriptLoader2.ts
More file actions
163 lines (142 loc) · 4.15 KB
/
ScriptLoader2.ts
File metadata and controls
163 lines (142 loc) · 4.15 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
import { uuid } from './Utils';
export type CallbackFn = () => void;
export interface ScriptItem {
src: string;
async?: boolean;
defer?: boolean;
nonce?: string;
}
interface Id {
id: string;
}
const injectScriptTag = (doc: Document, item: ScriptItem & Id, handler: (id: string, err?: unknown) => void) => {
const scriptTag = doc.createElement('script');
scriptTag.referrerPolicy = 'origin';
scriptTag.type = 'application/javascript';
scriptTag.id = item.id;
scriptTag.src = item.src;
scriptTag.async = item.async ?? false;
scriptTag.defer = item.defer ?? false;
scriptTag.nonce = item.nonce;
const loadHandler = () => {
scriptTag.removeEventListener('load', loadHandler);
scriptTag.removeEventListener('error', errorHandler);
handler(item.src);
};
const errorHandler = (err: unknown) => {
scriptTag.removeEventListener('load', loadHandler);
scriptTag.removeEventListener('error', errorHandler);
handler(item.src, err);
};
scriptTag.addEventListener('load', loadHandler);
scriptTag.addEventListener('error', errorHandler);
if (doc.head) {
doc.head.appendChild(scriptTag);
}
};
interface ScriptState {
id: string;
src: string;
done: boolean;
error?: unknown;
handlers: ((src: string, err?: unknown) => void)[];
}
const createDocumentScriptLoader = (doc: Document) => {
let lookup: Record<string, ScriptState> = {};
const scriptLoadOrErrorHandler = (src: string, err?: unknown) => {
const item = lookup[src];
item.done = true;
item.error = err;
for (const h of item.handlers) {
h(src, err);
}
item.handlers = [];
};
const loadScripts = (items: ScriptItem[], success: () => void, failure?: (err: unknown) => void) => {
// eslint-disable-next-line no-console
const failureOrLog = (err: unknown) => failure !== undefined ? failure(err) : console.error(err);
if (items.length === 0) {
failureOrLog(new Error('At least one script must be provided'));
return;
}
let successCount = 0;
let failed = false;
const loaded = (_src: string, err?: unknown) => {
if (failed) {
return;
}
if (err) {
failed = true;
failureOrLog(err);
} else if (++successCount === items.length) {
success();
}
};
for (const item of items) {
const existing = lookup[item.src];
if (existing) {
if (existing.done) {
loaded(item.src, existing.error);
} else {
existing.handlers.push(loaded);
}
} else {
// create a new entry
const id = uuid('tiny-');
lookup[item.src] = {
id,
src: item.src,
done: false,
error: null,
handlers: [ loaded ],
};
injectScriptTag(doc, { id, ...item }, scriptLoadOrErrorHandler);
}
}
};
const deleteScripts = () => {
for (const item of Object.values(lookup)) {
const scriptTag = doc.getElementById(item.id);
if (scriptTag != null && scriptTag.tagName === 'SCRIPT') {
scriptTag.parentNode?.removeChild(scriptTag);
}
}
lookup = {};
};
const getDocument = () => doc;
return {
loadScripts,
deleteScripts,
getDocument
};
};
type DocumentScriptLoader = ReturnType<typeof createDocumentScriptLoader>;
const createScriptLoader = () => {
const cache: DocumentScriptLoader[] = [];
const getDocumentScriptLoader = (doc: Document) => {
let loader = cache.find((l) => l.getDocument() === doc);
if (loader === undefined) {
loader = createDocumentScriptLoader(doc);
cache.push(loader);
}
return loader;
};
const loadList = (doc: Document, items: ScriptItem[], delay: number, success: () => void, failure?: (err: unknown) => void) => {
const doLoad = () => getDocumentScriptLoader(doc).loadScripts(items, success, failure);
if (delay > 0) {
setTimeout(doLoad, delay);
} else {
doLoad();
}
};
const reinitialize = () => {
for (let loader = cache.pop(); loader != null; loader = cache.pop()) {
loader.deleteScripts();
}
};
return {
loadList,
reinitialize
};
};
export const ScriptLoader = createScriptLoader();