Next.js and Lazy Hydration. Keep the HTML but drop the Javascript

Zack Jackson
5 min readOct 15, 2021

Code splitting can only get us so far, and how it works means you end up loading a lot of JS you don't really need right then and there. Why download the footer code when I'm looking at the header?

Code splitting has served us well, its lets us eliminate a good amount of unused payload from an application. But… its not perfect.

In the case of react, code split SSR, and all the libraries that exist are more or less founded on the same mechanism first created 5 years ago. We track if an import was executed during render and push its identifier into a map, then correlate that identifier against the client-side build to know what client javascript to send down in the SSR response.

For those who don't know, everyone who uses SSR is using two independent webpack builds, one for the server and another for the browser. So the server needs some way to create a relational mapping of what it executed and what the browser is going to need to execute.

The problem is.. I don't need all that javascript right away — mostly, I just want the HTML for SEO.

DLAYS, Download As You Scroll

Next.js is subject to the same problem as everyone else, if it's in the HTML render, the JS is on the page.

I've used LazyHydration for a long time as a half measure to improve performance. The idea being I don't execute and hydrate parts of the page till some point in the future, but I keep the HTML from the original render around. The problem is that the 1:1 mapping of what the server executed and what the client must download is still preserved, so even if I suppress hydration and save on runtime overhead — I'm still downloading useless javascript

Download as you scroll attempts to mitigate this problem by preserving the markup but filtering out the corresponding chunks from the server response. As the name suggests, only downloading the JS chunks and hydrating those elements when the user begins to scroll them into view — thus reducing the amount of code you need to load at startup.

Why download the footer JS if I'm looking at the top of the page?



Zack Jackson

Infra Architect @ ByteDance. Creator of Module Federation. Specializing in Bundler and Javascript Orchestration at scale.