Improve SSR hydration performance #6204
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Closes #5623. This is that PR rebased with logging removed. Thanks to @jonatansberg for paving the way on this!
Also closes #4309
Background
This PR improves SSR hydration performance through minimizing DOM mutations during hydration by avoiding de- and reattaching nodes during hydration. This should fix #1067, fix #4308, fix #5108, and fix #4975.
In order for this to work I added a new new "hydration mode". This way it's possible to maintain the detach by default behavior during hydration without modifying the generated component output. There might be better ways to do this if we reconsider fragment creation (as suggested in #3898 and #4219) but that would be a significant undertaking.
The existing append, insert and detached methods have been modified to track which nodes are claimed during hydration. That way unclaimed nodes can then removed from the DOM at the end of hydration without touching the remaining nodes.
In order for this to work the append, insert and detach methods have also been made idempotent (i.e. "upserts") in order to allow attaching an already attached DOM node.
Results
Initial local benchmarks against johnells.se (which runs on Sapper) shows a 50% reduction of LCP when running Lighthouse, which results in decent PageSpeed score improvement.
Production benchmarks on the SvelteKit app at https://c3.ventures/ show a PageSpeed score improvement from 92 to 99.