Skip to content

Commit 261c8b1

Browse files
feat(hydration): allow fine tuning of lazy hydration strategy triggers (#11530)
1 parent 63689ed commit 261c8b1

File tree

2 files changed

+23
-26
lines changed

2 files changed

+23
-26
lines changed

packages/runtime-core/src/hydrationStrategies.ts

+22-25
Original file line numberDiff line numberDiff line change
@@ -15,35 +15,32 @@ export type HydrationStrategy = (
1515
forEachElement: (cb: (el: Element) => any) => void,
1616
) => (() => void) | void
1717

18-
export type HydrationStrategyFactory<Options = any> = (
18+
export type HydrationStrategyFactory<Options> = (
1919
options?: Options,
2020
) => HydrationStrategy
2121

22-
export const hydrateOnIdle: HydrationStrategyFactory = () => hydrate => {
23-
const id = requestIdleCallback(hydrate)
24-
return () => cancelIdleCallback(id)
25-
}
26-
27-
export const hydrateOnVisible: HydrationStrategyFactory<string | number> =
28-
(margin = 0) =>
29-
(hydrate, forEach) => {
30-
const ob = new IntersectionObserver(
31-
entries => {
32-
for (const e of entries) {
33-
if (!e.isIntersecting) continue
34-
ob.disconnect()
35-
hydrate()
36-
break
37-
}
38-
},
39-
{
40-
rootMargin: isString(margin) ? margin : margin + 'px',
41-
},
42-
)
43-
forEach(el => ob.observe(el))
44-
return () => ob.disconnect()
22+
export const hydrateOnIdle: HydrationStrategyFactory<number> =
23+
(timeout = 10000) =>
24+
hydrate => {
25+
const id = requestIdleCallback(hydrate, { timeout })
26+
return () => cancelIdleCallback(id)
4527
}
4628

29+
export const hydrateOnVisible: HydrationStrategyFactory<
30+
IntersectionObserverInit
31+
> = opts => (hydrate, forEach) => {
32+
const ob = new IntersectionObserver(entries => {
33+
for (const e of entries) {
34+
if (!e.isIntersecting) continue
35+
ob.disconnect()
36+
hydrate()
37+
break
38+
}
39+
}, opts)
40+
forEach(el => ob.observe(el))
41+
return () => ob.disconnect()
42+
}
43+
4744
export const hydrateOnMediaQuery: HydrationStrategyFactory<string> =
4845
query => hydrate => {
4946
if (query) {
@@ -58,7 +55,7 @@ export const hydrateOnMediaQuery: HydrationStrategyFactory<string> =
5855
}
5956

6057
export const hydrateOnInteraction: HydrationStrategyFactory<
61-
string | string[]
58+
keyof HTMLElementEventMap | Array<keyof HTMLElementEventMap>
6259
> =
6360
(interactions = []) =>
6461
(hydrate, forEach) => {

packages/vue/__tests__/e2e/hydration-strat-visible.html

+1-1
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@
3535

3636
const AsyncComp = defineAsyncComponent({
3737
loader: () => Promise.resolve(Comp),
38-
hydrate: hydrateOnVisible(rootMargin + 'px')
38+
hydrate: hydrateOnVisible({rootMargin: rootMargin + 'px'})
3939
})
4040

4141
createSSRApp({

0 commit comments

Comments
 (0)