useScriptLoader.ts
1.78 KB
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import { useEffect, useState } from 'react'
interface ScriptOptions {
src: string
async?: boolean
defer?: boolean
id?: string
}
interface UseScriptLoaderResult {
loading: boolean
error: Error | null
success: boolean
isUniApp?: boolean
}
export default function useScriptLoader(options: ScriptOptions): UseScriptLoaderResult {
const [loading, setLoading] = useState(false)
const [error, setError] = useState<Error | null>(null)
const [success, setSuccess] = useState(false)
useEffect(() => {
// 检查脚本是否已存在
const existingScript = options.id
? document.getElementById(options.id)
: document.querySelector(`script[src="${options.src}"]`)
if (existingScript) {
setSuccess(true)
return
}
// 创建脚本元素
const script = document.createElement('script')
script.src = options.src
if (options.async) {
script.async = true
}
if (options.defer) {
script.defer = true
}
if (options.id) {
script.id = options.id
}
const handleLoad = () => {
setLoading(false)
setSuccess(true)
}
const handleError = (err: ErrorEvent) => {
setLoading(false)
setError(new Error(`Script load error for ${options.src}: ${err.message}`))
}
script.addEventListener('load', handleLoad)
script.addEventListener('error', handleError)
// 添加脚本到页面
document.body.appendChild(script)
setLoading(true)
// 清理函数
return () => {
script.removeEventListener('load', handleLoad)
script.removeEventListener('error', handleError)
if (script.parentNode) {
script.parentNode.removeChild(script)
}
}
}, [options.src, options.async, options.defer, options.id])
return { loading, error, success }
}