-
-
Notifications
You must be signed in to change notification settings - Fork 36
/
useScript.ts
212 lines (201 loc) · 6.59 KB
/
useScript.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
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
import { NetworkEvents, hashCode } from '@unhead/shared'
import type {
DomRenderTagContext,
Head,
HeadEntryOptions,
Script,
ScriptInstance,
UseScriptInput,
UseScriptOptions,
UseScriptResolvedInput,
} from '@unhead/schema'
import { defu } from 'defu'
import { getActiveHead } from './useActiveHead'
const UseScriptDefaults: Script = {
defer: true,
fetchpriority: 'low',
}
const requestIdleCallback: Window['requestIdleCallback'] = typeof window === 'undefined'
? (() => {}) as any
: (globalThis.requestIdleCallback || ((cb) => {
const start = Date.now()
const idleDeadline = {
didTimeout: false,
timeRemaining: () => Math.max(0, 50 - (Date.now() - start)),
}
return setTimeout(() => { cb(idleDeadline) }, 1)
}))
/**
* Load third-party scripts with SSR support and a proxied API.
*
* @experimental
* @see https://unhead.unjs.io/usage/composables/use-script
*/
export function useScript<T>(_input: UseScriptInput, _options?: UseScriptOptions<T>): T & { $script: ScriptInstance<T> } {
const input: UseScriptResolvedInput = typeof _input === 'string' ? { src: _input } : _input
const options = _options || {}
const head = options.head || getActiveHead()
if (!head)
throw new Error('No active head found, please provide a head instance or use the useHead composable')
// TODO warn about non-src / non-key input
const id = input.key || hashCode(input.src || (typeof input.innerHTML === 'string' ? input.innerHTML : ''))
const key = `use-script.${id}`
if (head._scripts?.[id])
return head._scripts[id]
async function transform(entry: Head): Promise<Head> {
const script = await (options.transform || (input => input))(entry.script![0] as UseScriptResolvedInput)
const ctx = { script }
await head!.hooks.callHook('script:transform', ctx)
return { script: [ctx.script] }
}
function maybeHintEarlyConnection(rel: 'preconnect' | 'dns-prefetch') {
if (
// opt-out
options.skipEarlyConnections
// must be a valid absolute url
|| !input.src.includes('//')
// must be server-side
|| !head!.ssr
)
return
const key = `use-script.${id}.early-connection`
head!.push({
link: [{ key, rel, href: new URL(input.src).origin }],
}, { mode: 'server' })
}
const script: ScriptInstance<T> = {
id,
status: 'awaitingLoad',
loaded: false,
remove() {
if (script.status === 'loaded') {
script.entry?.dispose()
script.status = 'removed'
head.hooks.callHook(`script:updated`, hookCtx)
delete head._scripts?.[id]
return true
}
return false
},
waitForLoad() {
return new Promise<T>((resolve) => {
if (script.status === 'loaded')
// @ts-expect-error untyped
resolve(options.use())
function watchForScriptLoaded({ script }: { script: ScriptInstance<T> }) {
if (script.id === id && script.status === 'loaded') {
script.loaded = true
resolve(options.use?.() as T)
head!.hooks.removeHook('script:updated', watchForScriptLoaded)
}
}
head.hooks.hook('script:updated', watchForScriptLoaded)
})
},
load() {
if (script.status !== 'awaitingLoad')
return script.waitForLoad()
script.status = 'loading'
head.hooks.callHook(`script:updated`, hookCtx)
script.entry = head.push({
script: [
// async by default
{ ...UseScriptDefaults, ...input, key },
],
}, {
...options as any as HeadEntryOptions,
// @ts-expect-error untyped
transform,
head,
})
head._scripts = defu(head._scripts, {
[id]: script,
})
return script.waitForLoad()
},
}
const hookCtx = { script }
NetworkEvents.forEach((fn) => {
// clone fn
const _fn = typeof input[fn] === 'function' ? input[fn].bind({}) : null
input[fn] = (e: Event) => {
script.status = fn === 'onload' ? 'loaded' : fn === 'onerror' ? 'error' : 'loading'
head.hooks.callHook(`script:updated`, hookCtx)
_fn && _fn(e)
head._scripts = defu(head._scripts, {
[id]: script,
})
}
})
let trigger = options.trigger
if (trigger) {
const isIdle = trigger === 'idle'
if (isIdle) {
// we don't need idle trigger for server
if (head.ssr)
trigger = 'manual'
else
// won't work in a SSR environment
trigger = new Promise<void>(resolve => requestIdleCallback(() => resolve()))
}
// never resolves
trigger === 'manual' && (trigger = new Promise(() => {}))
// check trigger is a promise
trigger instanceof Promise && trigger.then(script.load)
// if we're lazy it's likely it will load within the first 10 seconds, otherwise we just prefetch the DNS for a quicker load
maybeHintEarlyConnection(isIdle ? 'preconnect' : 'dns-prefetch')
}
else {
script.load()
// safe to preconnect as we'll load this script quite early
maybeHintEarlyConnection('preconnect')
}
function resolveInnerHtmlLoad(ctx: DomRenderTagContext) {
// we don't know up front if they'll be innerHTML or src due to the transform step
if (ctx.tag.key === key) {
if (ctx.tag.innerHTML) {
setTimeout(() => {
// trigger load event
script.status = 'loaded'
head!.hooks.callHook('script:updated', hookCtx)
typeof input.onload === 'function' && input.onload(new Event('load'))
}, 5 /* give inline script a chance to run */)
}
head!.hooks.removeHook('dom:renderTag', resolveInnerHtmlLoad)
}
}
head.hooks.hook('dom:renderTag', resolveInnerHtmlLoad)
// 3. Proxy the script API
const instance = new Proxy({}, {
get(_, fn) {
const stub = options.stub?.({ script, fn })
if (stub)
return stub
if (fn === '$script')
return script
return (...args: any[]) => {
// third party scripts only run on client-side, mock the function
if (head.ssr || !options.use)
return
// TODO mock invalid environments
if (script.loaded) {
const api = options.use()
// @ts-expect-error untyped
return api[fn](...args)
}
else {
return script.waitForLoad().then(
(api) => {
// @ts-expect-error untyped
return api[fn](...args)
},
)
}
}
},
}) as any as T & { $script: ScriptInstance<T> }
// 4. Providing a unique context for the script
head._scripts = head._scripts || {}
head._scripts[id] = instance
return instance
}