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

Open
wants to merge 13 commits into
base: trunk
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 34 additions & 8 deletions packages/interactivity/src/init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,38 @@ export const initialVdom = new WeakMap< Element, ComponentChild[] >();

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

const intersectionObserver = new window.IntersectionObserver(
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();
}

if ( ! hydratedIslands.has( node ) ) {
const fragment = getRegionRootFragment( node );
const vdom = toVdom( node );
await splitTask();
hydrate( vdom, fragment );
await splitTask();
}
}
},
{
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]`
);
Expand All @@ -45,13 +77,7 @@ export const init = async () => {
} );

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