Web performance
The browser turns HTML and CSS into pixels in a fixed order, and anything that blocks that order makes the page slow. Core Web Vitals measure three things users feel - how fast the main content shows (LCP), how fast the page reacts (INP) and how much it jumps (CLS). Measure with real user data, then fix the biggest cause first.
Author: bezzad
Contents
The problem: a product page that feels broken
Our online shop has a new product page. On the developer’s laptop it is fast. Real users on mid-range phones say something else:
- The big product photo shows up after four seconds. Until then the page is mostly empty.
- The “Add to cart” button does nothing for a moment after a tap. Some users tap twice and get two items.
- The page jumps. A banner loads late and pushes the button down, so users tap the wrong thing.
These are three different problems with three different fixes. To find them, we first need to know how the browser draws a page.
How the browser shows a page
The browser goes through the same steps for every page:
- Parse HTML into the DOM. The DOM is a tree of all elements on the page.
- Parse CSS into the CSSOM. The CSSOM is a tree of all style rules.
- Build the render tree. It joins the DOM and the CSSOM and keeps only what is visible. An element with display none is not in it.
- Layout. The browser calculates the size and position of every box.
- Paint. It fills in the pixels: text, colors, borders, images.
- Composite. It puts the painted layers together in the right order and shows them on the screen.
Two things follow from this:
- The browser cannot paint without CSS. If it painted early, the page would flash without styles. So CSS in the head is render-blocking: nothing shows until it is downloaded and parsed.
- Later changes repeat steps. If JavaScript changes the width of a box, the browser must run layout, paint and composite again. If it changes only the transform or opacity of a layer, it can often skip layout and paint.
Render-blocking CSS and scripts
A normal script tag in the head stops the HTML parser. The browser must download the script and run it before it reads the next line of HTML. The reason: the script may change the document while it is being parsed.
There are three better ways to load a script:
<!-- Blocks parsing: avoid in the head -->
<script src="/js/analytics.js"></script>
<!-- Downloads in parallel, runs after parsing, in order -->
<script defer src="/js/cart.js"></script>
<!-- Downloads in parallel, runs as soon as it arrives, any order -->
<script async src="/js/ads.js"></script>
<!-- Module scripts are deferred by default -->
<script type="module" src="/js/app.js"></script>
- Use defer for your own scripts that need the DOM or need to run in order. Deferred scripts run before the DOMContentLoaded event.
- Use async for independent scripts, like analytics, that do not depend on other scripts.
- A module script (type module) is deferred by default. You do not need to add defer to it.
- For CSS, keep the main stylesheet small. Put only the styles for the first screen in it, and load the rest later if you can.
Core Web Vitals
Google defines three numbers that match what users feel. A page “passes” when 75% of real page loads are in the good range. This is the 75th percentile.
| Metric | What it measures | Good |
|---|---|---|
| LCP (Largest Contentful Paint) | When the largest image or text block in the first screen is drawn | 2.5 seconds or less |
| INP (Interaction to Next Paint) | How long the page takes to show a response after a click, tap or key press | 200 ms or less |
| CLS (Cumulative Layout Shift) | How much visible content moves without the user asking | 0.1 or less |
INP replaced the older FID metric in March 2024. FID measured only the delay of the first interaction. INP looks at the interactions during the whole visit.
Fixing LCP: the hero image
On the product page, the LCP element is the big product photo. It was slow for two reasons:
- It was lazy-loaded. A lazy image waits until the browser knows it is near the screen. For the main image this only adds delay.
- The browser found it late and gave it a low priority, next to many small icons.
<!-- Bad: the main image waits -->
<img src="/img/mug-800.avif" loading="lazy" alt="Blue coffee mug">
<!-- Good: load it now, with high priority -->
<img src="/img/mug-800.avif" fetchpriority="high"
width="800" height="800" alt="Blue coffee mug">
- Never lazy-load the LCP image. Lazy loading is for images below the first screen.
- Add fetchpriority high so the browser downloads it before less important files.
- Put the image in the HTML. If JavaScript adds it later, or it is a CSS background, the browser finds it late. In that case a preload link in the head helps.
- Make the server fast too. LCP can never be faster than the first byte of HTML.
Fixing INP: long tasks
The browser has one main thread. It runs your JavaScript, handles clicks and draws frames. A long task is any task that runs for more than 50 ms. While it runs, a tap must wait.
On our product page, a click on “Add to cart” updated the cart, recalculated recommendations and sent analytics, all in one task. The fix is to do the urgent part first, then give the main thread back:
// Give the main thread a chance to paint and handle input.
function yieldToMain(): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, 0));
}
async function onAddToCart(productId: string): Promise<void> {
updateCartBadge(productId); // what the user waits for
await yieldToMain(); // the browser can paint now
updateRecommendations(productId);
await yieldToMain();
sendAnalytics('add_to_cart', productId);
}
- Do the visible update first. The user sees the new cart count fast.
- Yield between pieces of work. Each piece is now a short task, and input does not wait long.
- Some browsers have a scheduler yield method made for this. The setTimeout version works everywhere.
- Do less work. Heavy work that does not touch the DOM can move to a Web Worker.
Fixing CLS: reserve space
Content moves when the browser does not know its size ahead of time.
<!-- The browser knows the ratio before the image loads -->
<img src="/img/mug-400.avif" width="400" height="400" alt="Blue coffee mug">
/* Keep space for a banner that loads later */
.promo-banner {
min-height: 80px;
}
- Set width and height on images and videos. The browser uses them to compute the aspect ratio and keeps the space free. CSS can still make the image responsive.
- Reserve space for banners, ads and embeds that load later.
- Do not insert content above content the user is already looking at, unless the user asked for it.
- Web fonts can shift text when they replace the fallback font. Choose a fallback with a similar size.
Layout thrashing
Reading a layout value, like offsetHeight, needs an up-to-date layout. If you just changed a style, the browser must run layout now, in the middle of your code. Doing this in a loop forces many layouts.
const cards = document.querySelectorAll<HTMLElement>('.product-card');
// Bad: read, write, read, write... one forced layout per card
for (const card of cards) {
const h = card.offsetHeight; // read
card.style.height = `${h + 20}px`; // write
}
// Good: read everything first, then write everything
const heights = [...cards].map((card) => card.offsetHeight);
cards.forEach((card, i) => {
card.style.height = `${heights[i] + 20}px`;
});
Animate transform and opacity
To move or fade something, animate transform and opacity. The browser can often do these on the compositor, without new layout or paint. Animating width, height, top or left runs layout on every frame and can stutter.
/* Good: slides the mini cart in without layout */
.mini-cart {
transform: translateX(100%);
transition: transform 200ms ease-out;
}
.mini-cart.open {
transform: translateX(0);
}
Images
Images are often most of the bytes on a shop page.
<img
src="/img/mug-800.jpg"
srcset="/img/mug-400.avif 400w, /img/mug-800.avif 800w, /img/mug-1600.avif 1600w"
sizes="(max-width: 600px) 100vw, 50vw"
width="800" height="800"
loading="lazy"
alt="Blue coffee mug">
- Use modern formats. AVIF and WebP are usually much smaller than JPEG for the same quality.
- Send the right size. The srcset attribute lists the files and their widths. The sizes attribute tells the browser how wide the image will be on the page. The browser picks the smallest file that is sharp enough.
- Lazy-load images below the first screen, like product cards further down the list. Never the hero image.
JavaScript bundle size
Every kilobyte of JavaScript must be downloaded, parsed and run, often on a slow phone. Big bundles hurt LCP and INP.
// Load the checkout code only when the user opens checkout.
async function openCheckout(): Promise<void> {
const { renderCheckout } = await import('./checkout');
renderCheckout(document.querySelector('#app')!);
}
- Code splitting. A dynamic import makes the bundler put that code in a separate file. It loads only when it is needed.
- Lazy routes. Split by page. The product list page does not need the checkout code. Frameworks have this built in, for example lazy in React or lazy-loaded routes in Angular and Vue Router.
- Tree shaking. The bundler removes exports that nobody imports. It works best with ES modules (import and export). Importing a whole library for one function can still pull in a lot, so check your bundle with a bundle analyzer.
Caching with hashed file names
The best request is one the browser does not make. Build tools add a hash of the content to each file name:
/assets/app.3f9a1c.js Cache-Control: public, max-age=31536000, immutable
/assets/styles.8b2e4d.css Cache-Control: public, max-age=31536000, immutable
/index.html Cache-Control: no-cache
- A hashed file never changes. If the content changes, the name changes. So the browser can keep it for a year.
- The HTML file is checked every time (no-cache means “ask the server before using the copy”). It points to the new file names after each deploy.
- Users get new code right after a deploy, and old files are still cached for fast repeat visits.
Measuring
Lab data
- Lighthouse and the Chrome DevTools Performance panel
- One device and one network, on your machine
- Repeatable. Good for finding the cause and testing a fix.
- A normal page-load test has no clicks, so it cannot measure INP. Total Blocking Time is a hint.
Field data (real users)
- Data from real visits, for example the Chrome UX Report or the web-vitals library
- Real phones, real networks, real interactions
- This is what the 75th percentile is calculated from
- Tells you that there is a problem, not always why
import { onLCP, onINP, onCLS } from 'web-vitals';
// Send each metric to our own endpoint.
function send(metric: { name: string; value: number }): void {
navigator.sendBeacon('/api/vitals', JSON.stringify(metric));
}
onLCP(send);
onINP(send);
onCLS(send);
- Start with field data. It shows which metric is bad, and on which pages.
- Reproduce it in the lab. Record the page in the Performance panel, with CPU throttling to act like a slower phone. Long tasks are marked in red.
- Fix the biggest cause, then measure again.
Common mistakes
| Mistake | Result | The right way |
|---|---|---|
| Lazy-loading the hero image | LCP gets slower | Load it normally with fetchpriority high |
| A normal script tag in the head | The parser stops; the page shows later | Use defer, async or a module script |
| Images without width and height | The page jumps when they load (CLS) | Always set width and height |
| One big click handler | Long task, slow response (INP) | Update the screen first, then yield |
| Read and write layout in one loop | Many forced layouts | Read all values first, then write |
| Animating width, top or left | Layout on every frame, stutter | Animate transform and opacity |
| One bundle for the whole app | Slow download and parsing | Code splitting and lazy routes |
| Trusting only Lighthouse on a fast laptop | Real users still have a slow page | Collect field data at the 75th percentile |
Summary in seven lines
- The browser builds the DOM and CSSOM, then the render tree, then does layout, paint and composite.
- CSS blocks rendering. A normal script blocks parsing. Use defer, async or a module script.
- Good Core Web Vitals: LCP 2.5 s or less, INP 200 ms or less, CLS 0.1 or less, at the 75th percentile of real page loads.
- For LCP, do not lazy-load the hero image and give it fetchpriority high. For INP, split long tasks and yield. For CLS, set image sizes and reserve space.
- Read layout values before you write styles, and animate only transform and opacity.
- Send small modern images with srcset and sizes, and split JavaScript by route.
- Cache hashed files for a long time, measure with real user data, and use the lab to find the cause.