({
id,
onReady,
removeOnUnmount = false,
...rest
}: UseLoadScript)
| 7 | } & ({ src: string } | { text: string }) |
| 8 | |
| 9 | export const useLoadScript = ({ |
| 10 | id, |
| 11 | onReady, |
| 12 | removeOnUnmount = false, |
| 13 | ...rest |
| 14 | }: UseLoadScript) => { |
| 15 | useEffect(() => { |
| 16 | if (document.getElementById(id)) { |
| 17 | onReady?.() |
| 18 | return |
| 19 | } |
| 20 | |
| 21 | const script = document.createElement("script") |
| 22 | |
| 23 | script.id = id |
| 24 | script.async = true |
| 25 | script.onload = () => onReady?.() |
| 26 | |
| 27 | if ("src" in rest) { |
| 28 | script.src = rest.src |
| 29 | } |
| 30 | |
| 31 | if ("text" in rest) { |
| 32 | script.text = rest.text |
| 33 | } |
| 34 | |
| 35 | document.body.appendChild(script) |
| 36 | |
| 37 | return () => { |
| 38 | if (removeOnUnmount) { |
| 39 | const script = document.getElementById(id) |
| 40 | |
| 41 | if (script) { |
| 42 | document.body.removeChild(script) |
| 43 | } |
| 44 | } |
| 45 | } |
| 46 | }, [id, onReady, removeOnUnmount, rest]) |
| 47 | } |
no outgoing calls
no test coverage detected