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
42 changes: 34 additions & 8 deletions packages/interactivity/src/init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,18 +29,44 @@ 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]`
);

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