-
-
Notifications
You must be signed in to change notification settings - Fork 260
Expand file tree
/
Copy pathloadScript.js
More file actions
26 lines (20 loc) · 723 Bytes
/
loadScript.js
File metadata and controls
26 lines (20 loc) · 723 Bytes
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
const isBrowser =
typeof window !== "undefined" && typeof window.document !== "undefined";
export default function loadScript(src, onSuccess, onError) {
if (!isBrowser) return;
const scriptEl = document.createElement("script");
scriptEl.setAttribute("src", src);
scriptEl.addEventListener("load", onSuccess);
scriptEl.addEventListener("error", onError);
document.body.appendChild(scriptEl);
return () => {
scriptEl.removeEventListener("load", onSuccess);
scriptEl.removeEventListener("error", onError);
};
}
export function removeScript(src) {
const existing = document.body.querySelectorAll(`script[src="${src}"]`);
existing.forEach((el) => {
document.body.removeChild(el);
});
}