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

Interactivity API: Defer hydration until node is scrolled near the viewport #58284

Draft
wants to merge 10 commits into
base: trunk
Choose a base branch
from
44 changes: 37 additions & 7 deletions packages/interactivity/src/init.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,17 +30,47 @@ function yieldToMain() {

// Initialize the router with the initial DOM.
export const init = async () => {
const pendingNodes = new Set();

const intersectionObserver = new window.IntersectionObserver(
Copy link
Member Author

Choose a reason for hiding this comment

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

If there are no nodes below, then this wouldn't need to be constructed in the first place.

async ( entries ) => {
for ( const entry of entries ) {
if ( ! entry.isIntersecting ) {
continue;
}

const node = entry.target;
intersectionObserver.unobserve( node );
pendingNodes.delete( node );
if ( pendingNodes.size === 0 ) {
intersectionObserver.disconnect();
}
Copy link
Member Author

@westonruter westonruter Jan 26, 2024

Choose a reason for hiding this comment

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

This would be problematic for islands that are added dynamically during client-side navigations. The IntersectionObserver may need to remain persistently, if init() isn't called again after new islands are added.


if ( ! hydratedIslands.has( node ) ) {
while ( window.navigator.scheduling?.isInputPending() ) {
await yieldToMain();
}
const fragment = getRegionRootFragment( node );
const vdom = toVdom( node );
await yieldToMain();
hydrate( vdom, fragment );
await yieldToMain();
}
}
},
{
root: null, // To watch for intersection relative to the device's viewport.
rootMargin: '100% 0% 100% 0%', // Intersect when within 1 viewport approaching from top or bottom.
threshold: 0.0, // As soon as even one pixel is visible.
}
);

const nodes = document.querySelectorAll(
`[data-${ directivePrefix }-interactive]`
);

for ( const node of nodes ) {
if ( ! hydratedIslands.has( node ) ) {
await yieldToMain();
const fragment = getRegionRootFragment( node );
const vdom = toVdom( node );
await yieldToMain();
hydrate( vdom, fragment );
}
pendingNodes.add( node );
intersectionObserver.observe( node );
}
};
Loading