til.duyet.net
Search…
Create hook to inject JS script
1
import { useEffect } from "react"
2
​
3
export const useInjectScript = (src: string) =>
4
useEffect(() => {
5
// @ts-ignore
6
if (window.__custom_injected__) return
7
// @ts-ignore
8
window.__custom_injected__ = true
9
​
10
const script = document.createElement("script")
11
script.src = src
12
script.defer = true
13
​
14
const onScriptError = () => script.remove()
15
script.addEventListener("error", onScriptError)
16
​
17
document.body.appendChild(script)
18
}, [])
Copied!
1
import { useInjectScript } from './useInjectScript'
2
​
3
const Component = () => {
4
useInjectScript('https://duyet.net/x/lib.js')
5
6
return (...)
7
}
Copied!
Copy link
Edit on GitHub