日本語

Flushing HTML Early to Reduce LCP in Core Web Vitals

​​Core Web Vitals​Chrome,HTML,Node.js,Playwright,web-vitals

On a page that sends no HTML until the server finishes its database work, that wait is added directly to the LCP (Largest Contentful Paint) in Core Web Vitals. If you send the parts that don't depend on the data (the <head> and the hero image) first, and send the rest later, the browser can start loading the image while the server is still working. On a mock page that waits 800ms for data, the median LCP measured with web-vitals dropped from 2,312ms to 1,504ms.

This technique applies when a page built on the server, such as with server-side rendering (SSR), is slow to display, and when the LCP breakdown shows a long TTFB. I also cover how sending the wrong range can fail to help, and how inserting gzip compression can break the benefit.

Note

The test environment was Ubuntu 24.04, Node.js 22.23.4, web-vitals 6.2.3, and Playwright 1.63.0. The browser was Chrome for Testing 153, which ships with Playwright. The server was written with Node.js's http module (localhost:8080, HTTP/1.1), and the database work was a mock that just waits 800ms. The hero image was a 1200×675, roughly 277KB JPEG. I opened each page with Playwright at a 412px viewport, throttled downstream to 1.6Mbps using Chrome DevTools Protocol network emulation, and measured each page five times. I did not test streaming in frameworks such as React, HTTP/2 or HTTP/3, delivery through a CDN or reverse proxy, browsers other than Chrome, or real user data (field data).

Sending everything at once adds the wait to LCP

The web.dev guide to optimizing LCP splits LCP into four parts: the time until the first byte of HTML arrives (TTFB), the delay before the browser starts loading the LCP image (load delay), the time to load the image (load duration), and the delay before the image is rendered (render delay). The same guide says the frontend can't start anything until the backend returns the first byte.

First, I prepared a page that reads the article data and only then sends the HTML all at once.

js
async buffered(res) {
  const a = await loadArticle(); // takes 800ms
  res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });
  res.end(head({ preload: false }) + hero + article(a));
},

head() returns everything from <!doctype html> through the opening <body> tag, including the <head> that loads the CSS and web-vitals. hero is a <header> containing the hero image's <img>, and article() builds the body from the data. On this page, the LCP element was the hero image (html>body>header>img) in every run.

Write the early part with res.write

In Node.js's http module, calling res.write() sends everything written so far. The Node.js documentation for response.write() says the first res.write() sends the headers along with the first chunk of the body, and each later call is sent as a separate chunk. My test page did not set Content-Length, so the response went out with Transfer-Encoding: chunked.

The following page writes the head and hero image first, then writes the rest of the body after the data is loaded and ends the response.

js
async 'flush-hero'(res) {
  res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });
  res.write(head({ preload: false }) + hero); // send without waiting for data
  const a = await loadArticle();              // takes 800ms
  res.end(article(a));
},

I used a small script (chunks.mjs) built on Node.js http.get to record when each chunk arrived and how big it was. The all-at-once page delivered 1,057 bytes in one chunk at 816ms. The early-flush page delivered 762 bytes at 20ms, then the remaining 295 bytes at 820ms.

text
$ node chunks.mjs /buffered
/buffered  headers 815ms  status=200 transfer-encoding=chunked content-encoding=-
  chunk 816ms  1057 bytes
  end 817ms
$ node chunks.mjs /flush-hero
/flush-hero  headers 19ms  status=200 transfer-encoding=chunked content-encoding=-
  chunk 20ms  762 bytes
  chunk 820ms  295 bytes
  end 821ms

How far you flush changes how much LCP drops

I compared three pages that flush different ranges against the page that sends everything at once. Every value in the table is the median of five runs.

Approach LCP TTFB Load delay Image load time FCP
Send everything at once 2,312ms 803.5ms 14.7ms 1,484.0ms 1,004ms
Flush only the head 2,208ms 2.1ms 802.6ms 1,391.8ms 820ms
Flush only the head, preload the image 1,504ms 1.9ms 10.9ms 1,479.9ms 824ms
Flush the head and hero image 1,504ms 1.8ms 11.1ms 1,479.2ms 188ms

When only the head was flushed, TTFB fell to 2.1ms, but LCP dropped by only 104ms. The <img> sits in the part that is sent later, so the browser doesn't find the image until the body arrives. The 800ms spent waiting for data just moved from TTFB into load delay. Image load time also fell, from 1,484.0ms to 1,391.8ms.

When the hero image's <img> was flushed too, load delay dropped to 11.1ms and LCP came to 1,504ms. If the hero image markup can't be written until the data is ready, adding <link rel="preload" href="/hero.jpg" as="image" fetchpriority="high"> to the early <head> also gives 1,504ms. The web.dev guide to LCP optimization recommends making the LCP image discoverable from the HTML and preloading it when it is referenced only from external CSS or JavaScript.

Even with the same LCP, the time to first content (FCP) differed. The preload page took 824ms, while the page that flushed the hero image took 188ms. On the preload page, the contents of <body> (the hero image and the article) were in the part sent later. In my Node.js client, that part arrived at 814ms.

With gzip, the data isn't sent early unless you call flush()

On a page that compresses its response with gzip, the compression stream can hold on to the data you wrote instead of sending it. The flush section of the Node.js zlib documentation says that calling .flush() on a compression stream outputs all the data that can be output at that point, which may reduce compression efficiency.

I made two pages that pass through zlib.createGzip() and write up to the hero image before sending the rest. The only difference is whether gz.flush() is called. The test server always responds with gzip and ignores the request's Accept-Encoding.

js
res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'content-encoding': 'gzip' });
const gz = createGzip();
gz.pipe(res);
gz.write(head({ preload: false }) + hero);
gz.flush(); // without this, the part written above stays buffered
const a = await loadArticle();
gz.end(article(a));

On the page without flush(), only 10 bytes arrived at 14ms, and the HTML itself arrived at 815ms. On the page with flush(), 470 bytes arrived at 17ms.

text
$ node chunks.mjs /gzip-noflush
/gzip-noflush  headers 13ms  status=200 transfer-encoding=chunked content-encoding=gzip
  chunk 14ms  10 bytes
  chunk 815ms  590 bytes
  end 816ms
$ node chunks.mjs /gzip-flush
/gzip-flush  headers 17ms  status=200 transfer-encoding=chunked content-encoding=gzip
  chunk 17ms  10 bytes
  chunk 17ms  470 bytes
  chunk 818ms  148 bytes
  end 819ms

In the browser, the LCP of the page without flush() was 2,308ms, almost the same as the page that sends everything at once (2,312ms). The page with flush() came in at 1,508ms. I call flush() only once, right after writing the early part.

Stacked bar chart of the LCP breakdown for five approaches. Sending everything at once, gzip without flush, and flushing only the head are each about 2.2 to 2.3 seconds. Adding preload and flushing through the hero image are each 1,504ms
LCP breakdown (median of five runs). Gray on the left is TTFB and load delay; light blue is image load time
Warning

Even on the page without flush(), web-vitals reported a TTFB of 2.3ms (and time_starttransfer from curl was 0.001152 seconds). TTFB measures when the first byte arrives, so it drops as soon as the headers and the first 10 bytes arrive. Don't conclude that the HTML arrived early just because TTFB got shorter. Check LCP and the load delay in the breakdown too.

After you send early, you can't change the status code

The first res.write() sends the status code and headers. I built a page that failed to load the data after the early write and then called res.writeHead(500). Node.js threw ERR_HTTP_HEADERS_SENT (Cannot write headers after they are sent to the client). Checking with curl -i, the status was still 200 OK, and the error message appeared at the end of the body. The response was as follows (I omitted the date line and the part of the body from <head> through the hero image).

text
$ curl -s -i http://localhost:8080/flush-error
HTTP/1.1 200 OK
content-type: text/html; charset=utf-8
Connection: keep-alive
Keep-Alive: timeout=5
Transfer-Encoding: chunked

(省略)
<main><p>記事を読み込めませんでした。</p></main>
</body>
</html>

On a page that you plan to flush early, finish any logic that decides the status code, such as returning 404 or redirecting, before the first res.write(). The web.dev guide to optimizing TTFB notes that browsers process HTML as it arrives, so the first part should be sent as early as possible. If you use a framework, check whether it can split the HTML into chunks the way React's streaming does, as described in that same guide.

​Posted by 86