-
Notifications
You must be signed in to change notification settings - Fork 341
Expand file tree
/
Copy pathuseLoadScript.ts
More file actions
77 lines (68 loc) · 1.86 KB
/
Copy pathuseLoadScript.ts
File metadata and controls
77 lines (68 loc) · 1.86 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
import { useEffect, useState } from "react";
/**
* Hook to load external script.
* @param src - Source url to load.
* @param onLoad - Success callback.
* @param onError - Error callback.
*/
export function useLoadScript(src: string) {
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<Error | null>(null);
const [isSuccess, setIsSuccess] = useState(false);
const onLoad = () => {
setIsLoading(false);
setError(null);
setIsSuccess(true);
};
const onError = (error: Error | null) => {
setError(error);
setIsLoading(false);
setIsSuccess(false);
};
useEffect(() => {
if (!document) {
const error = new Error(
`[ScriptLoadingError] document not defined when attempting to load ${src}`,
);
onError(error);
return;
}
// Find script tag with same src in DOM.
const foundScript = document.querySelector<HTMLScriptElement>(
`script[src="${src}"]`,
);
// Call onLoad if script marked as loaded.
if (foundScript?.dataset.loaded) {
onLoad();
return;
}
// Create or get existed tag.
const script = foundScript || document.createElement("script");
// Set src if no script was found.
if (!foundScript) {
script.src = src;
}
// Mark script as loaded on load event.
const onLoadWithMarker = () => {
script.dataset.loaded = "1";
onLoad();
};
script.addEventListener("load", onLoadWithMarker);
script.addEventListener("error", (err) => {
console.error("Failed to load script:", src, err);
const error = new Error(
`[ScriptLoadingError] Failed to load script: ${src}`,
);
onError(error);
});
// Add to DOM if not yet added.
if (!foundScript) {
document.head.append(script);
}
}, []);
return {
isLoading,
error,
isSuccess,
};
}