From 645c945a36f19374e7aa8ffd0f06c6506b643543 Mon Sep 17 00:00:00 2001 From: Weston Ruter Date: Wed, 24 Jan 2024 16:29:44 -0800 Subject: [PATCH] Break long hydration task in interactivity init --- packages/interactivity/src/init.js | 28 +++++++++++++++++++--------- 1 file changed, 19 insertions(+), 9 deletions(-) diff --git a/packages/interactivity/src/init.js b/packages/interactivity/src/init.js index d749003b86f49d..fd3bf272737b6b 100644 --- a/packages/interactivity/src/init.js +++ b/packages/interactivity/src/init.js @@ -21,15 +21,25 @@ export const getRegionRootFragment = ( region ) => { return regionRootFragments.get( region ); }; +function yieldToMain() { + return new Promise( ( resolve ) => { + // TODO: Use scheduler.yield() when available. + setTimeout( resolve, 0 ); + } ); +} + // Initialize the router with the initial DOM. export const init = async () => { - document - .querySelectorAll( `[data-${ directivePrefix }-interactive]` ) - .forEach( ( node ) => { - if ( ! hydratedIslands.has( node ) ) { - const fragment = getRegionRootFragment( node ); - const vdom = toVdom( node ); - hydrate( vdom, fragment ); - } - } ); + 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 ); + hydrate( vdom, fragment ); + } + } };