Design and frontend · Intermediate · 24 min
How to Improve Largest Contentful Paint (LCP) on Your Website
By Padding · Updated 15 Nov 2026
Chrome DevTools · Core Web Vitals · demo checked in Chromium 159 · Node.js 26
You will measure Largest Contentful Paint on a deliberately slow page, find which of its four parts is wasting time, fix it by making the hero image discoverable early and by serving a smaller one, and learn how to check the result with field data, because 2.5 seconds is the line between good and not good.
On this page
Largest Contentful Paint (LCP) is the time from the start of a page load until the largest piece of content in the visible area has been drawn. That content is usually a hero image or a big heading. It is the closest single number to "when did the page look loaded to the visitor", and it is one of Google's three Core Web Vitals, which feed into search ranking along with how people experience your site.
web.dev, the web performance guidance from the Chrome team, sets the thresholds. An LCP of 2.5 seconds or less is good, between 2.5 and 4.0 seconds needs improvement, and more than 4.0 seconds is poor. A site passes when three quarters of its page loads meet the target, with phones and desktops counted separately. A single fast load on your laptop proves nothing, so the last step covers how to look at real visitors' numbers.
This tutorial makes the problem concrete. You will run a tiny local site that is slow on purpose, measure its LCP, work out which part of the load is to blame, and apply two of the fixes that matter most.
Step 1 · Know what LCP measures and what counts
LCP tracks the largest of these elements that is visible in the first screen, and it updates as bigger ones appear until the visitor interacts:
<img>elements, and<image>elements inside an<svg>.<video>elements, using the poster image or the first frame.- Elements with a background image loaded with
url(), but not CSS gradients. - Block-level elements that contain text.
Web.dev splits an LCP into four parts that add up to the total, and the split tells you what to fix. Time to first byte (TTFB) is how long the server takes to start answering. Resource load delay is the gap between the TTFB and the moment the browser starts fetching the LCP resource. Resource load duration is how long that download takes. Element render delay is the gap between the download finishing and the element appearing on screen. As a guideline, web.dev suggests about two fifths of the LCP for TTFB, under a tenth for load delay, about two fifths for load duration and under a tenth for render delay. Treat these shares as a way to spot the outlier, not as budgets.
If your LCP element is text, the middle two parts are zero, and the work is in TTFB, render-blocking CSS and web fonts. If it is an image, all four matter. The demo below uses an image, because that is the most common case.
Step 2 · Build a slow demo site
You need a page whose timings you control. Make a folder and generate two images. The script writes random-noise PNG files, which do not compress, so their sizes are predictable: 800 by 400 pixels is about 960 kB and 400 by 200 is about 240 kB. A real photograph would be smaller, but the principle is the same:
mkdir -p ~/lcp-demo/public
cd ~/lcp-demo
cat > make-images.mjs <<'JS'
import { writeFileSync } from 'node:fs'
import { randomFillSync } from 'node:crypto'
import { deflateSync, crc32 } from 'node:zlib'
function chunk(type, data) {
const length = Buffer.alloc(4)
length.writeUInt32BE(data.length)
const body = Buffer.concat([Buffer.from(type), data])
const checksum = Buffer.alloc(4)
checksum.writeUInt32BE(crc32(body))
return Buffer.concat([length, body, checksum])
}
function noisePng(width, height) {
const row = width * 3 + 1
const raw = Buffer.alloc(row * height)
for (let y = 0; y < height; y++) randomFillSync(raw, y * row + 1, width * 3)
const header = Buffer.alloc(13)
header.writeUInt32BE(width, 0)
header.writeUInt32BE(height, 4)
header[8] = 8 // bit depth
header[9] = 2 // RGB
return Buffer.concat([
Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]),
chunk('IHDR', header),
chunk('IDAT', deflateSync(raw)),
chunk('IEND', Buffer.alloc(0)),
])
}
writeFileSync('public/hero-800.png', noisePng(800, 400))
writeFileSync('public/hero-400.png', noisePng(400, 200))
JS
node make-images.mjs
ls -l publicNow the server. It sends files from public and imitates a slow connection in two ways: it waits before answering (100 ms for pages, 700 ms for the stylesheet, 50 ms for anything else), and it sends images at 500 kB per second. Those are the only numbers in this tutorial that come from the demo. The server refuses any path that leaves the public folder:
cat > server.mjs <<'JS'
import { createServer } from 'node:http'
import { readFile } from 'node:fs/promises'
import path from 'node:path'
const root = path.resolve('public')
const delays = { '/slow.html': 100, '/better.html': 100, '/best.html': 100, '/style.css': 700 }
const BYTES_PER_SECOND = 500_000
const types = { '.html': 'text/html', '.css': 'text/css', '.png': 'image/png' }
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
createServer(async (req, res) => {
const name = new URL(req.url, 'http://localhost').pathname
const file = path.join(root, name === '/' ? '/slow.html' : name)
if (!file.startsWith(root + path.sep)) return res.writeHead(403).end()
let body
try {
body = await readFile(file)
} catch {
return res.writeHead(404).end()
}
await wait(delays[name] ?? 50)
res.writeHead(200, {
'content-type': types[path.extname(file)] ?? 'application/octet-stream',
'content-length': body.length,
'cache-control': 'no-store',
})
if (path.extname(file) !== '.png') return res.end(body)
const size = 16_384
for (let i = 0; i < body.length; i += size) {
res.write(body.subarray(i, i + size))
await wait((size / BYTES_PER_SECOND) * 1000)
}
res.end()
}).listen(8080, '127.0.0.1', () => console.log('listening on http://127.0.0.1:8080'))
JSThe first page puts the hero image in the stylesheet as a CSS background, a common pattern. The three pages share a stylesheet and differ only in how the hero is included:
cat > public/style.css <<'CSS'
body { margin: 0; padding: 1rem; font-family: system-ui, sans-serif; }
h1 { margin: 0 0 0.5rem; font-size: 1.5rem; }
.hero-bg { width: 400px; height: 200px; background: url(hero-800.png) center / cover; }
.hero-img { display: block; width: 400px; height: 200px; }
CSS
cat > public/slow.html <<'HTML'
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Field notes</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>Field notes</h1>
<div class="hero-bg" role="img" aria-label="Decorative pattern"></div>
<p>Short notes from the garden.</p>
</body>
</html>
HTMLStart the server in a terminal, and leave it running:
node server.mjsCheck it worked
The terminal prints listening on http://127.0.0.1:8080. From a second terminal, check the first page:
curl -s -o /dev/null -w '%{http_code} %{size_download} bytes\n' http://127.0.0.1:8080/hero-400.pngThe output is 200 and a size close to 240,000 bytes. Open http://127.0.0.1:8080/slow.html in Chrome: the page shows a heading, a noisy rectangle that appears after a short wait, and a line of text.
Step 3 · Measure the baseline
The browser reports LCP through the PerformanceObserver API. In Chrome, open DevTools (F12), choose the Console, paste this and press Enter, then reload the page and wait a few seconds for the last line. Pasting into the console may need you to type allow pasting first:
new PerformanceObserver((list) => {
const entry = list.getEntries().at(-1)
console.log('LCP', Math.round(entry.startTime), 'ms', entry.element, entry.url)
}).observe({ type: 'largest-contentful-paint', buffered: true })The observer is called each time the browser finds a larger element, so the last line it prints is the final LCP. The element is the element and the url is the image behind it.
For a view of the whole load, use the Performance panel. In recent versions of Chrome, open the Performance panel and choose Record and reload. The Timings track shows an LCP marker, and clicking it names the element. The panel's Insights list includes an LCP breakdown with the four parts from the first step. The exact buttons move between Chrome versions, so look for the LCP marker and the breakdown if a label differs. Lighthouse gives you the same number in a report, along with advice.
Check it worked
The console first prints a line for the text, which is drawn the moment the stylesheet arrives, and then a line starting with LCP and a number for the image, with div.hero-bg as the element and the address of hero-800.png. With the settings of this demo server, expect a value of about 3,100 ms, which is in the "needs improvement" band of web.dev's scale (between 2.5 and 4.0 seconds). The result varies by a hundred milliseconds or so between loads. The breakdown shows why: the browser cannot start downloading the image until it has fetched and read the stylesheet, which takes 700 ms, and only then spends about two seconds downloading it. That is resource load delay and load duration, the two parts that the next steps attack.
Step 4 · Make the image discoverable and give it priority
Browsers find resources to fetch by scanning the HTML early, before CSS and scripts have run. An image in a CSS background is only found once the stylesheet has arrived and the page has been laid out, so its download starts late. An <img> in the HTML is found at once and downloaded in parallel with the stylesheet. Web.dev's advice is to make the LCP image discoverable in the initial HTML. If you cannot, for example when a script or stylesheet decides which image to show, add a <link rel="preload" as="image"> for it.
Add a second page that uses an <img>, and mark it fetchpriority="high", a hint that this one is more important than other images. Use it on one or two images at most, because if everything is high priority, nothing is:
cat > public/better.html <<'HTML'
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Field notes</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>Field notes</h1>
<img class="hero-img" src="hero-800.png" width="400" height="200" fetchpriority="high" alt="">
<p>Short notes from the garden.</p>
</body>
</html>
HTMLThe width and height attributes reserve the space so the page does not shift when the image arrives, which protects another Core Web Vital, Cumulative Layout Shift. The empty alt marks the image as decorative. Give a real image a real description.
Check it worked
Run the console snippet again on http://127.0.0.1:8080/better.html. The element is now img.hero-img, and the LCP drops by roughly the 700 ms the stylesheet used to cost, to about 2,400 ms, because the download no longer waits for the CSS. That is under the 2.5 second line, but only just, and a slower phone would be over it. Do not put loading="lazy" on this image. Lazy loading tells the browser to postpone the fetch until layout is known, and web.dev says doing it to the LCP image always adds unnecessary load delay. Lazy loading is for images below the fold.
Step 5 · Serve a smaller image
The page shows the hero at 400 by 200 CSS pixels, but the file is 800 by 400, four times the pixels. That wasted download is the "resource load duration" part of the LCP. Offer the browser a choice with srcset and sizes. srcset lists candidate files with their widths, and sizes says how wide the image will be displayed, so the browser can pick the smallest file that still looks sharp on this screen:
cat > public/best.html <<'HTML'
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Field notes</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>Field notes</h1>
<img class="hero-img" src="hero-400.png"
srcset="hero-400.png 400w, hero-800.png 800w" sizes="400px"
width="400" height="200" fetchpriority="high" alt="">
<p>Short notes from the garden.</p>
</body>
</html>
HTMLOn a standard screen, 400 CSS pixels need a 400-pixel-wide file, so the browser picks hero-400.png. On a screen with twice the pixel density, it picks the 800-pixel one, because it needs the pixels to stay sharp. The src is the fallback for browsers that ignore srcset. Image formats matter as much as dimensions: web.dev recommends AVIF or WebP over older formats, compression, and serving images from a CDN close to the visitor. This demo uses noise PNGs, which no modern format can shrink much, so it shows only the resizing.
Check it worked
Measure http://127.0.0.1:8080/best.html the same way. The LCP is now about 900 ms, an element of img.hero-img with the address of hero-400.png. In DevTools' Network panel, the hero request is about 240 kB instead of about 960 kB.
Troubleshooting
If the numbers are very different, other work on the machine can add noise. Close heavy tabs and measure each page three times, taking the median. DevTools can also add its own slowdowns, so close extra panels, and run in an Incognito window so extensions do not interfere. If the LCP element is the heading or the paragraph and not the image, you read the console too early: the text was drawn first, and the browser reports the largest element it has drawn so far. Wait until the image has appeared. The last entry is the one that counts.
Step 6 · Find what is left and check real visitors
Even best.html waits for the stylesheet before it can draw anything: CSS blocks rendering, and this server delays it by 700 ms. That is the "element render delay" and TTFB side of the budget. On a real site you would shrink and inline small critical CSS, drop render-blocking scripts from the <head> or give them defer, and cut server response time with caching and a CDN. Web.dev's guide lists these under each of the four parts, and the order in which to look is the same each time: TTFB first, then load delay, load duration and render delay.
A local test shows whether a change helps, but the number that counts is what your visitors see. Look at field data:
- PageSpeed Insights shows your page's field data, if enough people with Chrome have visited it, from the Chrome User Experience Report (CrUX), next to a lab run. Search Console's Core Web Vitals report groups your pages by status.
- To collect your own, add Google's
web-vitalsJavaScript library, which reports LCP as visitors experience it, and send it to your analytics:
import { onLCP } from 'web-vitals'
onLCP((metric) => {
navigator.sendBeacon('/vitals', JSON.stringify({ name: metric.name, value: metric.value }))
})- Compare the 75th percentile of the field numbers, split by phone and desktop, with the 2.5 s line. After a fix ships, give it a few weeks, since CrUX reports a rolling 28 days.
Step 7 · Keep LCP from getting worse again
Most regressions come from the same few causes. Check them in code review:
- A new hero or banner added as a CSS background or injected by a script. Use an
<img>in the HTML, or preload it. loading="lazy"on an image that is in the first screen, orfetchpriority="high"on five images.- Large images uploaded straight from a camera. Resize and compress on upload, and serve several sizes with
srcset. - A new font that blocks text from showing. Use
font-display: swap, and preload the main font file. - A script or stylesheet added to the
<head>withoutdeferormedia.
Run Lighthouse on your main templates in CI, or watch the web-vitals data, so a change that costs half a second is noticed in a day, not a quarter.
Step 8 · Clean up
Stop the server with Ctrl+C in its terminal and delete the demo folder:
cd ~
rm -rf ~/lcp-demoNext steps
- Lay pages out so they do not shift: build page layouts with CSS Grid.
- Serve images and pages from a CDN close to your visitors: host a static site on Cloudflare Pages.
- Style the page without render-blocking surprises: set up Tailwind CSS 4 with Vite.
- Read web.dev's articles "Largest Contentful Paint" and "Optimize Largest Contentful Paint", which this tutorial follows.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials