Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

perf(hydration): avoid observer if element is in viewport #11639

Merged
merged 10 commits into from
Sep 18, 2024
19 changes: 18 additions & 1 deletion packages/runtime-core/src/hydrationStrategies.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,16 @@ export const hydrateOnIdle: HydrationStrategyFactory<number> =
return () => cancelIdleCallback(id)
}

function elementIsVisibleInViewport(el: Element) {
const { top, left, bottom, right } = el.getBoundingClientRect()
// eslint-disable-next-line no-restricted-globals
const { innerHeight, innerWidth } = window
return (
((top > 0 && top < innerHeight) || (bottom > 0 && bottom < innerHeight)) &&
((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth))
)
}

export const hydrateOnVisible: HydrationStrategyFactory<
IntersectionObserverInit
> = opts => (hydrate, forEach) => {
Expand All @@ -37,7 +47,14 @@ export const hydrateOnVisible: HydrationStrategyFactory<
break
}
}, opts)
forEach(el => ob.observe(el))
forEach(el => {
if (elementIsVisibleInViewport(el)) {
hydrate()
ob.disconnect()
return () => {}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

After looking at the benchmark I think this is worthwhile, but the implementation needs some adjustments.

Right now there is no way to break out of the forEach loop, returning an empty function here doesn't do anything. We need to refactor forEach so that the loop breaks if the callback returns false.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see. I'll look into refactoring the function, thank you!

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is the proposed fix functional?

}
ob.observe(el)
})
return () => ob.disconnect()
}

Expand Down