forked from TanStack/tanstack.com
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseScript.ts
More file actions
39 lines (31 loc) · 827 Bytes
/
useScript.ts
File metadata and controls
39 lines (31 loc) · 827 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
27
28
29
30
31
32
33
34
35
36
37
38
39
import * as React from 'react'
export function useScript(
attrs: React.HTMLProps<HTMLScriptElement>,
opts?: {
delay?: number
}
) {
const attrsStringified = JSON.stringify(attrs)
React.useEffect(() => {
const addScript = () => {
const script = document.createElement('script')
Object.assign(script, attrs)
document.body.appendChild(script)
return () => {
document.body.removeChild(script)
}
}
if (opts?.delay) {
let remove: ReturnType<typeof addScript> | undefined
const timeout = setTimeout(() => {
remove = addScript()
}, opts.delay)
return () => {
clearTimeout(timeout)
remove?.()
}
}
return addScript()
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [attrsStringified])
}