-
Notifications
You must be signed in to change notification settings - Fork 42
/
index.ts
37 lines (33 loc) · 1.04 KB
/
index.ts
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
import { useEffect, useRef, useState } from '@wordpress/element';
/**
* Add a script tag to body
*
* @param {string} scriptSource Source URL of the script to be loaded.
* @returns {HTMLScriptElement} The script tag.
*/
export const useScript = (
scriptSource: string,
): { hasLoaded: boolean; scriptElement: HTMLScriptElement | null } => {
const scriptElement = useRef<HTMLScriptElement | null>(null);
const [scriptLoaded, setScriptLoaded] = useState<boolean>(false);
useEffect(() => {
if (window) {
scriptElement.current = document.createElement('script');
scriptElement.current.src = scriptSource;
scriptElement.current.async = true;
scriptElement.current.type = 'text/javascript';
scriptElement.current.addEventListener(
'load',
() => {
setScriptLoaded(true);
},
{ once: true, passive: true },
);
document.body.appendChild(scriptElement.current);
}
return () => {
scriptElement.current?.remove();
};
}, [scriptSource]);
return { hasLoaded: scriptLoaded, scriptElement: scriptElement.current };
};