Open History to see the last commit
1import type { HydrationPrefetchStrategy } from './types'
2β
3const idleType = 'idle'
4β
5export type IdleHydrationOptions = {
6 timeout?: number
7}
8β
9export function idle(
10 options: IdleHydrationOptions = {},
11): HydrationPrefetchStrategy<typeof idleType> {
12 const timeout = options.timeout ?? 2000
13β
14 return {
15 _t: idleType,
16 _s: ({ gate, prefetch }) => {
17 const schedule = globalThis as unknown as {
18 requestIdleCallback?: (
19 callback: IdleRequestCallback,
20 options?: IdleRequestOptions,
21 ) => number
22 cancelIdleCallback?: (handle: number) => void
23 }
24 const callback = prefetch ?? gate!.resolve
25β
26 if (schedule.requestIdleCallback) {
27 const handle = schedule.requestIdleCallback(callback, { timeout })
28 return () => schedule.cancelIdleCallback?.(handle)
29 }
30β
31 const timeoutId = globalThis.setTimeout(callback, timeout)
32 return () => globalThis.clearTimeout(timeoutId)
33 },
34 }
35}