-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathresourceLoader.js
More file actions
660 lines (602 loc) · 16.4 KB
/
resourceLoader.js
File metadata and controls
660 lines (602 loc) · 16.4 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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
/**
* ResourceLoader.js Library v1.0.0
* https://github.dev/peterbenoit/ResourceLoader.js
*
* ResourceLoader is a flexible JavaScript library that allows for dynamic loading of
* resources like JavaScript, CSS, images, JSON, and other file types. It supports
* features like error handling, retries, cache busting, and concurrency control,
* making it suitable for various applications.
*
* Released under the MIT License.
*
* Copyright (c) 2024 Peter Benoit
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* @author Peter Benoit
* @version 1.0.0
* @license MIT
*/
(function (root, factory) {
const instance = factory(root);
if (typeof module === "object" && module.exports) {
module.exports = instance;
}
if (root && typeof root === "object") {
root.ResourceLoader = instance;
}
})(typeof globalThis !== "undefined" ? globalThis : this, (root) => {
let resourceLoadedPromises = {};
let resourceStates = {};
let loggingLevel = "warn";
function setLoggingLevel(level) {
const validLevels = ["silent", "warn", "verbose"];
if (validLevels.includes(level)) {
loggingLevel = level;
} else {
console.warn(`Invalid log level: ${level}. Falling back to 'warn'.`);
loggingLevel = "warn";
}
}
function log(message, level = "verbose") {
if (loggingLevel === "verbose" && level === "verbose") {
console.log(message);
} else if (
loggingLevel === "warn" &&
(level === "warn" || level === "error")
) {
console.warn(message);
}
}
function categorizeError(error, fileType, url) {
if (error.name === "AbortError") {
return { type: "abort", message: `Fetch aborted for: ${url}` };
} else if (
typeof error.message === "string" &&
error.message.toLowerCase().includes("timeout")
) {
return { type: "timeout", message: `Timeout while loading: ${url}` };
} else if (
fileType &&
![
"js",
"css",
"json",
"jpg",
"jpeg",
"png",
"gif",
"svg",
"webp",
"woff",
"woff2",
"pdf",
"zip",
"bin",
"mp3",
"mp4",
"avi",
"webm",
"ogg",
"wav",
].includes(fileType)
) {
return {
type: "unsupported",
message: `Unsupported file type: ${fileType} for ${url}`,
};
} else {
return {
type: "network",
message: `Network error or resource not found: ${url}`,
};
}
}
function validateSecurityAttributes(element, fileType, attributes) {
if (fileType === "js" || fileType === "css") {
if (
attributes.crossorigin &&
!["anonymous", "use-credentials"].includes(attributes.crossorigin)
) {
log(
`Invalid "crossorigin" attribute for ${fileType} resource: ${attributes.crossorigin}. Using default "anonymous".`,
"warn"
);
element.crossOrigin = "anonymous";
}
}
if (fileType === "js" || fileType === "css") {
if (!attributes.integrity) {
log(
`"integrity" attribute missing for ${fileType} resource. This is required for secure resource loading.`,
"warn"
);
} else {
element.integrity = attributes.integrity;
}
}
}
function applyAttributes(element, attributes, fileType) {
Object.keys(attributes).forEach((key) => {
if (key in element) {
element.setAttribute(key, attributes[key]);
} else {
log(
`Invalid attribute "${key}" for element type "${element.tagName}". Skipping.`,
"warn"
);
}
});
validateSecurityAttributes(element, fileType, attributes);
}
function include(urls, options = {}) {
if (!Array.isArray(urls)) {
urls = [urls];
}
const {
attributes = {},
timeout = 10000,
cacheBusting = false,
cacheBustingQuery = `?_=${new Date().getTime()}`,
cacheBustingTypes = ["js", "css"],
restrictCacheBustingToLocal = true,
appendToBody = false,
crossorigin = false,
logLevel = "warn",
onError = null,
onSuccess = null,
retries = 0,
retryDelay = 1000,
deferScriptsUntilReady = true,
batchSize = 5,
maxConcurrency = 3,
priority = 0,
removeFailedElements = true,
} = options;
setLoggingLevel(logLevel);
const sortedUrls = urls.sort((a, b) => {
const priorityA = a.priority || 0;
const priorityB = b.priority || 0;
return priorityB - priorityA;
});
const getFileType = (url) => {
const urlWithoutParams = url.split("?")[0].split("#")[0];
const extension = urlWithoutParams.split(".").pop().toLowerCase();
if (
extension &&
extension.length <= 5 &&
extension !== urlWithoutParams
) {
return extension;
}
if (
url.includes("/json") ||
url.includes("jsonplaceholder") ||
url.includes("api")
) {
return "json";
}
if (
url.includes("/images") ||
url.includes("picsum") ||
url.includes("/img")
) {
return "png";
}
return extension;
};
const loadResource = (url, retryCount = 0) => {
if (resourceLoadedPromises[url]) {
return resourceLoadedPromises[url].promise;
}
resourceStates[url] = "loading";
const isLocalResource =
!!(root.location && root.location.origin) &&
url.startsWith(root.location.origin);
const fileType = getFileType(url);
const applyCacheBusting =
cacheBusting &&
(!restrictCacheBustingToLocal || isLocalResource) &&
cacheBustingTypes.includes(fileType);
const finalUrl = applyCacheBusting ? `${url}${cacheBustingQuery}` : url;
const controller = new AbortController();
const { signal } = controller;
const scheduleRetry = (resolve, reject) => {
if (retryCount < retries) {
log(`Retrying to load resource: ${finalUrl}`, "warn");
delete resourceLoadedPromises[url];
setTimeout(() => {
loadResource(url, retryCount + 1)
.then(resolve)
.catch(reject);
}, retryDelay);
return true;
}
return false;
};
const handleFailure = (categorizedError, resolve, reject) => {
resourceStates[url] = "unloaded";
if (onError) onError(categorizedError, url);
if (!scheduleRetry(resolve, reject)) {
reject(categorizedError);
}
};
let timedOut = false;
let startedLoading = false;
const promiseEntry = { cancel: null };
let rejectPromise;
promiseEntry.promise = new Promise((resolve, reject) => {
rejectPromise = reject;
const loadScriptWhenReady = () => {
const existingElement =
document.head.querySelector(
`[src="${finalUrl}"], [href="${finalUrl}"]`
) ||
document.body.querySelector(
`[src="${finalUrl}"], [href="${finalUrl}"]`
);
if (existingElement) {
log(`Resource already loaded: ${finalUrl}`, "verbose");
resourceStates[url] = "loaded";
resolve(finalUrl);
return;
}
let element;
let timeoutId;
const clearLoadTimeout = () => {
if (timeoutId) {
clearTimeout(timeoutId);
timeoutId = null;
}
};
const startLoadTimeout = () => {
timeoutId = setTimeout(handleTimeout, timeout);
};
const handleTimeout = () => {
if (timedOut) {
return;
}
timedOut = true;
controller.abort();
const error = new Error(`Timeout while loading: ${finalUrl}`);
const categorizedError = categorizeError(
error,
fileType,
finalUrl
);
if (element && startedLoading) {
element.remove();
log(
`Resource load aborted due to timeout: ${finalUrl}`,
"warn"
);
}
handleFailure(categorizedError, resolve, reject);
};
switch (fileType) {
case "js":
element = document.createElement("script");
element.src = finalUrl;
element.async = true;
if (crossorigin) {
element.crossOrigin = crossorigin;
}
break;
case "css":
element = document.createElement("link");
element.href = finalUrl;
element.rel = "stylesheet";
if (crossorigin) {
element.crossOrigin = crossorigin;
}
break;
case "json":
startLoadTimeout();
fetch(finalUrl, { signal })
.then((response) => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json(); // Ensure the response is parsed as JSON
})
.then((data) => {
if (!timedOut) {
clearLoadTimeout();
resourceStates[url] = "loaded";
resolve(data); // Resolve with the JSON data
if (onSuccess) onSuccess(data); // Trigger onSuccess
}
})
.catch((error) => {
if (timedOut) {
return;
}
clearLoadTimeout();
const categorizedError = categorizeError(
error,
fileType,
finalUrl
);
handleFailure(categorizedError, resolve, reject);
});
promiseEntry.cancel = () => {
clearLoadTimeout();
controller.abort();
};
return;
case "jpg":
case "jpeg":
case "png":
case "gif":
case "svg":
case "webp":
element = document.createElement("img");
element.src = finalUrl;
if (crossorigin) {
element.crossOrigin = crossorigin;
}
break;
case "woff":
case "woff2":
startLoadTimeout();
const fontFace = new FontFace(
"customFont",
`url(${finalUrl})`,
{
crossOrigin: crossorigin,
}
);
fontFace
.load()
.then(() => {
if (!timedOut) {
clearLoadTimeout();
document.fonts.add(fontFace);
resourceStates[url] = "loaded";
resolve();
}
})
.catch((error) => {
if (timedOut) {
return;
}
clearLoadTimeout();
const categorizedError = categorizeError(
error,
fileType,
finalUrl
);
handleFailure(categorizedError, resolve, reject);
});
return;
case "pdf":
case "zip":
case "bin":
case "mp3":
case "mp4":
case "avi":
case "webm":
case "ogg":
case "wav":
startLoadTimeout();
fetch(finalUrl, { signal })
.then((response) => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.blob();
})
.then((data) => {
if (!timedOut) {
clearLoadTimeout();
resourceStates[url] = "loaded";
resolve(data);
if (onSuccess) onSuccess(data); // Invoke onSuccess callback
}
})
.catch((error) => {
if (timedOut) {
return;
}
clearLoadTimeout();
const categorizedError = categorizeError(
error,
fileType,
finalUrl
);
handleFailure(categorizedError, resolve, reject);
});
promiseEntry.cancel = () => {
clearLoadTimeout();
controller.abort();
};
return;
default:
const error = new Error(`Unsupported file type: ${fileType}`);
reject(error);
log(
`Failed to load unsupported file type: ${finalUrl}`,
"error"
);
return;
}
applyAttributes(element, attributes, fileType);
startedLoading = true;
startLoadTimeout();
element.onload = () => {
if (!timedOut) {
clearLoadTimeout();
log(`Resource loaded from: ${finalUrl}`, "verbose");
resourceStates[url] = "loaded";
resolve();
if (onSuccess) onSuccess(url);
}
};
element.onerror = () => {
if (timedOut) {
return;
}
clearLoadTimeout();
const loadError = new Error(
`Failed to load resource from: ${finalUrl}`
);
const categorizedError = categorizeError(
loadError,
fileType,
finalUrl
);
log(`Failed to load resource from: ${finalUrl}`, "warn");
if (removeFailedElements && element && element.parentNode) {
element.parentNode.removeChild(element);
log(`Removed failed element: ${finalUrl}`, "verbose");
}
handleFailure(categorizedError, resolve, reject);
};
if (element.tagName) {
if (appendToBody && fileType === "js") {
document.body.appendChild(element);
} else {
document.head.appendChild(element);
}
}
promiseEntry.cancel = () => {
clearLoadTimeout();
controller.abort();
if (element && element.parentNode) {
element.parentNode.removeChild(element);
log(
`Loading cancelled and element removed: ${finalUrl}`,
"warn"
);
resourceStates[url] = "unloaded";
if (rejectPromise) {
rejectPromise({
type: "abort",
message: `Loading cancelled for: ${finalUrl}`,
});
}
}
};
};
if (
fileType === "js" &&
deferScriptsUntilReady &&
document.readyState !== "complete"
) {
root.addEventListener("DOMContentLoaded", () => {
log(
`Deferring script load until DOM ready: ${finalUrl}`,
"verbose"
);
loadScriptWhenReady();
});
} else {
loadScriptWhenReady();
}
});
resourceLoadedPromises[url] = promiseEntry;
return promiseEntry.promise;
};
function loadWithConcurrencyLimit(resources, loadFn, maxConcurrency) {
let index = 0;
const results = [];
const total = resources.length;
return new Promise((resolve, reject) => {
const startNext = () => {
if (index >= total) {
if (results.length === total) {
const hasFailures = results.some(
(result) => result && result.status === "rejected"
);
if (hasFailures) {
reject({
type: "aggregate",
message: "One or more resources failed to load.",
results,
});
} else {
resolve(results);
}
}
return;
}
const currentIndex = index++;
const url = resources[currentIndex];
loadFn(url)
.then(() => {
results[currentIndex] = { status: "fulfilled", value: url };
startNext();
})
.catch((error) => {
results[currentIndex] = {
status: "rejected",
reason: error,
url,
};
startNext();
});
};
// Start initial batch
for (let i = 0; i < Math.min(maxConcurrency, total); i++) {
startNext();
}
});
}
return loadWithConcurrencyLimit(sortedUrls, loadResource, maxConcurrency);
}
function unloadResource(url) {
const elements = document.querySelectorAll(
`[src="${url}"], [href="${url}"]`
);
elements.forEach((element) => element.remove());
if (resourceLoadedPromises[url]) {
delete resourceLoadedPromises[url];
log(`Resource ${url} unloaded and cache cleared.`, "verbose");
resourceStates[url] = "unloaded";
}
}
function cancelResource(url) {
if (resourceLoadedPromises[url] && resourceLoadedPromises[url].cancel) {
resourceLoadedPromises[url].cancel();
delete resourceLoadedPromises[url];
log(`Resource ${url} loading cancelled.`, "warn");
resourceStates[url] = "unloaded";
}
}
function cancelAll() {
Object.keys(resourceLoadedPromises).forEach((url) => {
if (resourceLoadedPromises[url] && resourceLoadedPromises[url].cancel) {
resourceLoadedPromises[url].cancel();
}
});
resourceLoadedPromises = {};
log("All resource loading operations cancelled.", "warn");
}
function getResourceState(url) {
return resourceStates[url] || "unloaded";
}
return {
include,
unloadResource,
cancelResource,
cancelAll,
getResourceState,
setLoggingLevel,
};
});