Bookmarks
ReferenceFrontendVerified

Web performance

Web performance is how quickly pages load and respond. This reference covers Core Web Vitals (LCP, INP, CLS), measurement, images, fonts and caching.

checked 1 Nov · next check 8 Nov · 50 min read

Sections
11
Reading
50 min
Languages
RU · UZ · EN
Written from
web.dev/performance

Check status of the reference

Verified 1 Nov · next check 8 Nov

The sections were compared with the release notes, the check found nothing, and all source links respond.

  1. Verified
  2. Scheduled check

What web performance is and how it works

Web performance is the speed of a page as the user experiences it: how soon the main content appears, how quickly the page responds to a click, and whether the layout jumps around. It is measured with metrics taken from real visits, not by the time of the load event.

The load time describes poorly what a person actually sees: a server can return an almost empty page instantly and show the content several seconds later. That is why the Chrome team, together with the W3C Web Performance Working Group, defined metrics around the questions users ask: has loading started, has useful content appeared, can I use the page, and does it run smoothly?

Speed is not a single number. The same page is fast on a new phone with a good connection and slow on a cheap phone with a poor one. Two pages with the same load time feel different if one shows content gradually and the other only at the very end. So metrics are collected from real visits (field data, or RUM, Real User Monitoring) and complemented by lab runs under identical conditions. For details, see the section “Measurement: field and lab”.

Speed affects revenue and search. The BBC lost an additional 10% of users for every extra second of loading, and at Vodafone a 31% improvement in LCP brought 8% more sales. For the page experience ranking signal, Google Search uses Chrome UX Report (CrUX) data on real visits.

Loading happens in stages, and each stage has its own metric. TTFB (Time to First Byte) is the time until the first byte of the server response. FCP (First Contentful Paint) is the first content painted, and LCP (Largest Contentful Paint) is the paint of the largest text block or image in the viewport. While a person uses the page, INP (Interaction to Next Paint) measures the delay of clicks, taps and key presses, and CLS (Cumulative Layout Shift) measures unexpected layout shifts. LCP, INP and CLS are the Core Web Vitals, and a page is assessed by them.

LCP, INP and CLS are the Core Web Vitals; TTFB and FCP help find the cause of a slow LCP.

How it differs from load testing and server monitoring

AspectWeb performanceLoad testingServer monitoring
What is checkedone person’s experience in the browser: content appearing, responsiveness, layout stabilityhow the system copes with many simultaneous users and requestshow the server behaves under load: response time, errors, memory
Loadan ordinary visitfrom minimal (smoke) to extreme (breakpoint)the load of real users
Measured withCrUX, your own RUM, Lighthouse, DevToolsload scripts, for example k6exporters and PromQL, Grafana dashboards
Key indicatorsLCP, INP and CLS at the 75th percentile of visitsnumber of virtual users (VUs) or throughput, and test durationresponse-time percentiles and error rate

Choose by symptom. If the page is slow for every visitor even on an idle server, it is a web performance problem. If it slows down only at peak hours, it is a load testing problem: see the “Load testing” reference. Server metrics and dashboards are covered in the “Prometheus and Grafana” reference.

What you need to know first

  • The “HTML and CSS” reference: the img, link and script tags, and the “Responsive layout” section
  • The JavaScript reference, the section “Asynchrony: promises, async and the event loop”, which underpins the discussion of long tasks
  • The “HTTP and REST” reference, the “Caching” section: the Cache-Control and ETag headers

Section sources

the section is written from these pages

Checklist

Go through the list before releasing a page and after major changes. Start with the group for the metric that misses its threshold at the 75th percentile; each item is explained in the working sections of this reference.

Measurement

  • Assess Core Web Vitals using field data at the 75th percentile, separately for phones and desktops
  • Collect your own RUM with the web-vitals library if the site is not in CrUX or you need to know the cause
  • Verify a fix in the lab before release (Lighthouse, the Performance panel), and after release in the field

Loading

  • Keep TTFB at around 0.8 s or less: remove unnecessary redirects and serve HTML through a CDN
  • Include scripts in head with defer or type="module"; without them, use only a small inline script
  • Remove unused CSS and @import, and inline critical styles in head
  • Use preconnect only for the most important third-party origins and dns-prefetch for the rest

Images and video

  • Serve the LCP image with an img tag directly in the HTML, without loading="lazy" and with fetchpriority="high"
  • Set width and height on every img and video
  • Serve AVIF or WebP with a JPEG fallback through picture, and sizes through srcset and sizes
  • Use loading="lazy" only for images and iframe elements below the first screen
  • Replace animated GIFs with video with the attributes autoplay muted loop playsinline

Fonts

  • Serve fonts only in WOFF2 and split them into subsets with unicode-range
  • Set font-display: swap for headings, optional for body text
  • Preload only first-screen fonts, in a single format and always with crossorigin

JavaScript

  • Break up tasks longer than 50 ms: await scheduler.yield() with a setTimeout fallback
  • Load code by route and on demand with import()
  • Remove third-party scripts with no clear benefit, and include the rest with async or defer

Layout stability and caching

  • Reserve space for ads and embeds with min-height or aspect-ratio
  • Animate transform, not top, left, width or height
  • Serve files with a hash in the name with Cache-Control: max-age=31536000, immutable, and HTML with no-cache and ETag
  • Do not add an unload handler or set Cache-Control: no-store on ordinary pages: this keeps them eligible for bfcache
  • Set a performance budget and check it in CI, for example with Lighthouse CI

Section sources

the section is written from these pages

Core Web Vitals: LCP, INP and CLS

Core Web Vitals are three metrics of user experience: LCP (loading speed), INP (responsiveness to actions) and CLS (layout stability). A page passes the assessment if, at the 75th percentile of visits, all three are in the “good” range: LCP up to 2.5 s, INP up to 200 ms, CLS up to 0.1.

MetricGoodNeeds improvementPoor
LCP≤ 2.5 s2.5–4 s> 4 s
INP≤ 200 ms200–500 ms> 500 ms
CLS≤ 0.10.1–0.25> 0.25

The assessment uses the 75th percentile of all visits to a page or site, separately for phones and desktops; the thresholds themselves are the same for both. If at least 75% of visits are in the “good” range, the page is good; if at least 25% are in the “poor” range, the page is poor. The 75th percentile is chosen so that three visits out of four get the target experience, while rare outliers on a bad network do not change the rating.

Example. A page has 100 phone visits: for 70, LCP is under 2.5 s; for 22, it is between 2.5 and 4 s; for 8, it is over 4 s. If you line up the visits by LCP, the 75th falls between 2.5 and 4 s, so the result is “needs improvement”: there are fewer than 75% good visits, and the poor ones (8%) are fewer than 25%.

LCP: when the main element is shown

LCP (Largest Contentful Paint) is the time from the start of navigation to the paint of the largest image, text block or video in the viewport. The following count as LCP element candidates:

  • img, using the first frame’s presentation time for animated images
  • image inside svg
  • video, using the poster or the first frame, whichever comes first
  • an element with a background loaded through url(), but not a gradient
  • a block-level element containing text

Size is only the visible part of the element, excluding margin, padding and borders; for a downscaled image, the smaller of the visible and intrinsic size is used. While the page loads, the browser reports a new candidate whenever an element larger than the previous one is painted. An image that has not yet loaded and text in a web font during the block period do not count as candidates. Chromium also excludes invisible elements with opacity: 0, full-screen backgrounds and placeholders. What LCP time consists of and how to find the culprit is covered in the section “Loading and the critical path”.

javascriptDevTools console
const observer = new PerformanceObserver((list) => {  for (const entry of list.getEntries()) {    // each new candidate is larger than the previous one    console.log('LCP:', entry.startTime, entry.element);  }});observer.observe({  type: 'largest-contentful-paint',  buffered: true,});

INP: responsiveness to actions

INP (Interaction to Next Paint) observes the latency of all mouse clicks, screen taps and key presses during a visit and takes the longest one; if there are many interactions, one longest is discarded for every 50. Scrolling and hovering are not counted, and if a person never clicks anything, there is no INP value. In JavaScript, INP is calculated from Event Timing API entries.

The latency of a single interaction runs from the action to the next frame with a visible result and consists of three parts:

  1. Input delay: from the action until the handlers start; it grows when the main thread is busy with another task.
  2. Processing duration: the work of all event handlers for this action.
  3. Presentation delay: from the end of the handlers until the next frame is shown.
If the main thread is free, input delay is close to zero, leaving the handlers and painting.

Example. A person clicked “Filter” while the main thread was still spending 120 ms parsing a script; the handler ran for 150 ms, and painting the frame took 30 ms. The latency is 300 ms; if it ends up as the page’s INP, that is “needs improvement”. The handler ran longest, so start with it; techniques for breaking up tasks are in the section “JavaScript and long tasks”.

INP replaced FID (First Input Delay) in March 2024. FID measured only the input delay of the first interaction, whereas INP measures all interactions in full, from the action to the frame.

CLS: unexpected layout shifts

A layout shift is a change in the starting position of a visible element between two frames. Shifts that follow one another with a gap of less than 1 s are grouped into a window of up to 5 s; CLS is the sum of the scores of the worst window over the whole lifetime of the page. CLS has no units.

A shift score is the share of the screen affected by the moved elements (impact fraction) multiplied by the share of the distance moved (distance fraction). Example: a block covering half the screen moved down by a quarter of the screen height. The old and new positions together occupy 75% of the screen, and the distance is 25% of its larger dimension: 0.75 × 0.25 = 0.1875. A single shift like this already puts the page in the “needs improvement” range.

Not counted are the appearance of a new element and resizing, if they do not shift other visible elements, and shifts within 500 ms after a click, tap or key press; such entries have the hadRecentInput flag. Animation with transform: translate() and transform: scale() causes no shifts, whereas changing top, left, width and height does.

javascriptDevTools console
const observer = new PerformanceObserver((list) => {  for (const entry of list.getEntries()) {    // shifts right after input are not part of CLS    if (!entry.hadRecentInput) {      console.log('Layout shift:', entry);    }  }});observer.observe({ type: 'layout-shift', buffered: true });

Supporting metrics

Three metrics are not part of Core Web Vitals but help find the cause of bad values:

MetricWhat it showsWhat it points to
TTFBtime until the first byte of the server responsea slow server response drags LCP down with it
FCPthe first paint of any contentresources that block rendering
TBT (Total Blocking Time)how long the main thread was blocked during loading; lab onlyfuture INP problems

Section sources

the section is written from these pages

Measurement: field and lab

Field data consists of measurements of real visits; lab data comes from running a page under set conditions on one device and one network. Only field data gives the Core Web Vitals assessment; the lab is for finding the cause and verifying a fix before release.

AspectFieldLab
Data sourcereal visits: CrUX or your own RUMa Lighthouse or DevTools run
What you geta distribution across visits, with the 75th percentile as the resulta single value and detailed diagnostics
Cachewarm on repeat visits, bfcache worksusually empty
ResponsivenessINP from real interactionsLighthouse does not measure INP; TBT is used instead
When to useto assess a page and choose what to fixto debug and verify a change before release

A lab run is one device, one network and one location, almost always a cold load. The field covers all devices, networks and ways of using the page. If the data disagrees, the field takes priority: it shows what users actually see.

Tools

ToolDataUse for
PageSpeed Insightsfield from CrUX and lab from Lighthousea first look at a URL and a whole origin, phone and desktop separately; other people’s sites can be viewed too; public URLs only
CrUX (Chrome UX Report)field: Chrome users, rolling 28 daysper-country data and metrics not available in other tools; BigQuery and API
Search Consolefield from CrUXgroups of similar pages; verified owners only
Lighthouselabauditing during development; Lighthouse CI for checks in CI
The Performance panel in DevToolslab, plus CrUX field data for comparisonlive metrics while using the page, tracing long tasks and shifts
The web-vitals libraryfield: your own RUMLCP, INP and CLS of your users, with causes

CrUX is an open dataset of real Chrome users. It includes only public pages and origins with enough visits. The data is a rolling 28-day window, so a fix does not show up in CrUX immediately. The dataset is available monthly in BigQuery at the origin level and daily through the API, for both URLs and origins.

The Lighthouse score

The Performance score is a weighted average of the scores of five metrics; since Lighthouse 10 it no longer includes TTI (Time to Interactive), and you should not make it a target. Lighthouse converts each metric to a score from 0 to 100 based on the distribution of real sites in HTTP Archive.

MetricWeight in the score
TBT (Total Blocking Time)30%
LCP25%
CLS25%
FCP10%
Speed Index10%

Colours: 0–49 is poor, 50–89 needs improvement, 90–100 is good. A perfect 100 is not expected: raising the score from 99 to 100 is as hard as going from 90 to 94. The score varies from run to run because of A/B tests, ads, network routes, a different device, browser extensions and antivirus software.

Your own RUM with web-vitals

The web-vitals library weighs about 3 KB after brotli compression and calculates metrics the same way as Google’s tools. It can be loaded late: it reads the entries accumulated before it loaded. The functions onLCP, onINP and onCLS call the callback when a value is ready; CLS and INP are reported again when the user leaves the tab, and after a return from bfcache all metrics are calculated anew.

bashin the project directory
npm install web-vitals
javascriptpage code
import { onCLS, onINP, onLCP } from 'web-vitals'; const queue = new Set();const addToQueue = (metric) => queue.add(metric); function flushQueue() {  if (queue.size === 0) return;  // send only the fields we need  const rows = [...queue].map((m) => ({    name: m.name, value: m.value, rating: m.rating, id: m.id,  }));  const body = JSON.stringify(rows);  // sendBeacon delivers the data even when the tab is closing  navigator.sendBeacon('/analytics', body);  queue.clear();} onCLS(addToQueue);onINP(addToQueue);onLCP(addToQueue); addEventListener('visibilitychange', () => {  if (document.visibilityState === 'hidden') flushQueue();});

The rating field already contains good, needs-improvement or poor, so there is no need to apply the thresholds by hand. On the server, calculate the 75th percentile for each metric. onLCP and onINP work in Chromium, Firefox and Safari; onCLS works only in Chromium. The web-vitals/attribution build adds the cause to a metric: the LCP element, the slow interaction, the element that shifted.

Worked example: good in the lab, poor in the field

PageSpeed Insights shows an LCP of 1.9 s in Lighthouse and 3.4 s at the 75th percentile of phones in the field. The tool is not wrong: field and lab measure different things. Check in order:

  1. Users have a different LCP element: a different screen size, a signed-in account, an A/B test, a link to the middle of the page. Capture the element with the attribution build.
  2. Users’ devices and networks are slower than Lighthouse emulates.
  3. CLS after loading: shifts during scrolling, for example from lazy-loaded images without dimensions, are invisible to Lighthouse.
  4. INP: TBT in the lab may be good, but on a site without a mobile layout the browser adds a 300 ms delay to every tap, which counts towards INP but not TBT.

The opposite case, where the field is better than the lab, is usually explained by repeat visits: they have a warm cache and bfcache works, whereas Lighthouse always loads the page from scratch.

Section sources

the section is written from these pages

Loading and the critical path

The critical rendering path is the sequence of steps from receiving the HTML to the first paint of the page. Render-blocking resources in the head lengthen it: CSS delays rendering, and a script without defer or async stops HTML parsing.

For the first paint, the browser needs part of the HTML, the CSS in the head and the synchronous scripts in the head. It does not wait for the rest of the HTML, fonts, images, scripts at the end of body, or CSS whose media attribute does not match the screen. The browser parses HTML as a stream, so the top of the page can appear before the bottom has arrived.

What blocks rendering and parsing

CSS is render-blocking: otherwise people would see an unstyled page. A script without async or defer is parser-blocking: it can change the DOM, so parsing stops while the script downloads and runs. To avoid losing that time, the preload scanner looks through the raw HTML and requests the resources it finds ahead of time. It cannot see:

  • images referenced from CSS through background-image
  • scripts inserted by JavaScript, and modules loaded with import()
  • markup that JavaScript renders on the client
  • styles pulled in with @import in CSS

Such resources are discovered late. The most common loss is a synchronous script in the head: the first paint waits for all of it. Here is what happens:

  1. The browser parses the HTML and meets a script tag with src in the head.
  2. Parsing stops while app.js downloads.
  3. The script runs.
  4. The browser parses the rest of the HTML.
  5. Only now can the first paint happen.

With defer, steps 2 and 3 move to the background: the script downloads during parsing and runs after it, so the first paint comes sooner.

type="module" behaves like defer by default.

defer, async and modules

How it is includedWhen it runsOrderBlocks HTML parsing
no attributesas soon as it downloadsas in the markupyes, while it downloads and runs
asyncright after it downloadsin download orderno, only while it downloads
deferafter HTML parsing, before DOMContentLoadedas in the markupno
type="module"like deferas in the markupno
htmldon’t do this
<head>  <link rel="stylesheet" href="/css/main.css">  <!-- HTML parsing waits for the script to download and run -->  <script src="/js/app.js"></script></head>
htmldo this
<head>  <link rel="stylesheet" href="/css/main.css">  <!-- downloads in parallel, runs after parsing -->  <script src="/js/app.js" defer></script></head>

CSS needs a different approach: styles are required for rendering, so the goal is to make them smaller. Remove unused rules, which the Coverage tab in DevTools shows, and minify the file. Replace @import with link: the browser finds a file referenced by @import only after downloading the first one. Small critical styles can be inlined in the head, but inlined CSS is not cached separately from the HTML.

Resource hints

Resource hints are written in the head as a link tag or sent in the Link HTTP header. They tell the browser what to do in advance:

HintWhat it doesWhen to use it
preconnectopens a connection to another origin in advancefor the most important third-party origins: a CDN, a font service
dns-prefetchonly resolves the name in DNS in advancefor less important domains: cheaper than preconnect
preloadrequests a resource of the current page right awayonly for critical resources that are discovered late: a font, an image from CSS, a resource from JS
modulepreloaddownloads, parses and compiles a module in advancefor the application entry module: the browser can fetch dependencies itself, but is not obliged to
prefetchloads a resource at low priority for the next navigationfor a page that almost everyone goes to next
htmlindex.html
<head>  <link rel="preconnect" href="https://cdn.example.com">  <!-- a font is a CORS resource: crossorigin is required -->  <link rel="preload" href="/fonts/inter.woff2" as="font"        crossorigin>  <link rel="dns-prefetch" href="https://stats.example.org">  <link rel="prefetch" href="/css/checkout.css" as="style"></head>

The fetchpriority attribute (high, low, auto) changes the fetch priority of link, img and script. The browser loads resources in two phases: critical ones first, until the blocking scripts have run, and in that phase low-priority resources may have to wait. Give high priority to one or two images, usually the LCP image: when many resources are marked high, they end up sharing the channel again. The same goes for preload: an excess of preloads takes bandwidth from what matters.

For the next navigation, besides prefetch of individual files, there are speculation rules: JSON rules inside <script type="speculationrules">. They list whole documents that the browser downloads ahead of time (prefetch) or even renders in the background (prerender). The value "eagerness": "moderate" defers speculation until the pointer hovers over a link (on a phone, until signs of intent such as a press). It is a hint, not an order: the browser may ignore it, for example when memory is low:

htmlindex.html
<script type="speculationrules">{  "prerender": [{    "where": { "href_matches": "/*" },    "eagerness": "moderate"  }]}</script>

TTFB: the server response

TTFB (Time to First Byte) comes before every other loading metric, and each extra millisecond is added to FCP and LCP. The target is 0.8 s or less; anything over 1.8 s is poor. The time goes on redirects (from http:// to https://, to a URL with or without a trailing slash, through link shorteners), on the route to a distant server without a CDN, on CDN cache misses caused by unique analytics parameters in the URL, and on the server itself. The Strict-Transport-Security (HSTS) header avoids the HTTP-to-HTTPS redirect: after the first visit the browser goes straight to HTTPS.

To see where the server spends its time, send a Server-Timing header. In DevTools it appears on the Network tab, and for real users it is in the navigation entry:

httpserver response
Server-Timing: db;desc="Database";dur=121.3, ssr;dur=212.2
javascriptDevTools console
const [nav] = performance.getEntriesByType('navigation');for (const entry of nav.serverTiming) {  console.log(entry.name, entry.description, entry.duration);}

A 103 Early Hints response lets the browser start loading critical CSS while the server prepares the HTML, but it masks a slow server in TTFB. Compression, caching and HTTP/2–3 on the server side are covered in the Nginx reference, in the section “Caching and compression”.

What LCP consists of

LCP time splits into four parts with no gaps: together they add up to the whole LCP. Two of them are delays, which you aim to reduce to zero; the other two are network loads, which are unavoidable.

PartWhat it isTarget, share of LCP
TTFBuntil the first byte of HTMLabout 40%
Resource load delayfrom TTFB to the start of loading the LCP resourceunder 10%
Resource load durationloading the image or font itselfabout 40%
Element render delayfrom the end of loading to rendering the elementunder 10%

The parts are visible in Lighthouse, in the Performance panel and in CrUX. Speeding up one part without looking at the others is pointless: if the element is hidden until JavaScript runs, a compressed image will only move time from loading to render delay.

A worked example: LCP of 3.1 s

An LCP breakdown in DevTools: TTFB 0.6 s, resource load delay 1.5 s, load duration 0.7 s, render delay 0.3 s. The load delay is almost half of LCP instead of 10%: the image is discovered late. The cause is a banner set as a CSS background, which the browser learns about only after downloading and parsing the styles. It is better to move the banner into an img; if that is not possible, preload it with high priority so that it loads together with the styles. Without the 1.4 s delay, LCP would be about 1.7 s.

htmlin <head>
<link rel="stylesheet" href="/css/main.css"><!-- the image from CSS loads together with the styles --><link rel="preload" as="image" href="/img/hero.avif"      type="image/avif" fetchpriority="high">

Section sources

the section is written from these pages

Images and video

The first-screen image is often the LCP element, so it must not be lazy-loaded: it should be visible right in the HTML and get high priority. All other images need dimensions to prevent layout shifts and a suitable format, and those below the first screen need loading="lazy".

The LCP image

  • An img tag with src or srcset right in the server’s HTML, not data-src, a CSS background or an element inserted by a script: otherwise the browser finds the image only after the CSS or JavaScript.
  • No loading="lazy": the browser lets a lazy image load only once layout confirms that it is within the screen bounds.
  • With fetchpriority="high" on one or two images, no more.
  • If the image is still in CSS or JavaScript, use link rel="preload" with fetchpriority="high".

Why priority matters: images do not block rendering, so even without lazy loading the browser does not give them the highest priority, and it gives images below the first screen a lower one. fetchpriority="high" hints which image is more important: its download starts earlier and gets more bandwidth. If you have to preload an image, set fetchpriority="high" on link rel="preload" as well.

htmlindex.html
<img src="/img/hero-1200.avif" alt="New collection"     width="1200" height="600" fetchpriority="high">

Dimensions against layout shifts

Before it loads, an image without width and height takes up 0×0 pixels, and then pushes the text apart. With the attributes, the browser calculates the aspect ratio (aspect-ratio: auto 1200 / 600) before the download and reserves the space, while CSS stretches the image to the column width. All variants in srcset must have the same aspect ratio; if a source inside picture has a different one, set width and height on the source too.

cssstyles.css
img {  max-width: 100%;  /* the height is calculated from width and height in the markup */  height: auto;}

Responsive sizes: srcset and sizes

An image in a 500 px container on a screen with a device pixel ratio (DPR) of 2 needs a file 1000 px wide; at DPR 3, 1500 px. The srcset attribute is a list of candidate files with their actual widths, and sizes is the width of the image on the page at different screen sizes. The browser uses them to choose a file itself.

htmlindex.html
<img src="/img/card-500.jpg" alt="Laptop" width="500" height="500"     srcset="/img/card-500.jpg 500w,             /img/card-1000.jpg 1000w,             /img/card-1500.jpg 1500w"     sizes="(min-width: 768px) 500px, 100vw">

On a 320 px wide phone with DPR 3, a full-width image takes up 960 physical pixels, and the browser picks card-1000.jpg; on a desktop with DPR 1 it picks card-500.jpg. Each variant is a separate cache entry, so a few sizes are usually enough. The srcset, sizes and picture markup is covered in detail in the HTML and CSS reference, in the section “Responsive layout”.

Formats

FormatCompressionWhen to use it
AVIFlossy and lossless; in tests it can save more than 50% compared with JPEGphotos and large images; a fallback format is required
WebPlossy and lossless, with transparency even when lossyworks in all modern browsers
JPEGlossyfallback for photos
PNGlosslessfallback for diagrams, text and sharp edges
SVGvector, losslessicons, logos and diagrams; not for photos
htmlindex.html
<picture>  <source type="image/avif" srcset="/img/photo.avif">  <source type="image/webp" srcset="/img/photo.webp">  <img src="/img/photo.jpg" alt="Office" width="800" height="533"></picture>

The browser takes the first source whose format it understands, and if there is none, the img. The alt, width and height attributes go on the img and apply to whichever source is chosen. Lossy compression is fine for photos, but it spoils sharp edges, lines and text.

Lazy loading

Lazy loading is the loading="lazy" attribute: the browser does not download an image or iframe while it is far from the viewport. Chromium starts loading ahead of time: 1,250 px away on a fast network and 2,500 px on a slow one. Use it only for what is below the first screen. A CSS background cannot be deferred this way: the attribute works only on img and iframe.

htmlindex.html
<!-- first screen: normal loading --><img src="/img/product-1.jpg" alt="Kettle" width="200" height="200"><!-- below the first screen --><img src="/img/product-7.jpg" alt="Toaster" width="200" height="200"     loading="lazy"><iframe src="https://www.example.com/map" width="600" height="400"        loading="lazy" title="Map"></iframe>

Video

An animated GIF weighs megabytes; the same content in a video is much lighter. To replace a GIF, remove the audio track and use autoplay muted loop playsinline. Load a video that the user starts themselves with preload="none" and a poster (poster): then the browser does not download it until the click. If the poster is the LCP element, preload it with fetchpriority="high".

htmlinstead of a GIF
<video autoplay muted loop playsinline width="640" height="360">  <source src="/media/demo.webm" type="video/webm">  <source src="/media/demo.mp4" type="video/mp4"></video>
bashin a terminal
# -an removes the audio: it is not needed to replace a GIFffmpeg -i demo.mov -an demo.webm

Embedding a third-party video player brings a lot of JavaScript: according to HTTP Archive, a YouTube embed on a typical site blocks the main thread for more than 1.7 s and hurts INP. Show a placeholder instead and load the player on click.

A worked example: a home page banner

Before: the banner is a single JPEG 2,400 px wide and weighing about 2 MB, the template sets loading="lazy" on all images, and there are no dimensions. A phone downloads the same file as a large monitor, loading starts late, and the text below the banner jumps. After:

htmldo this
<picture>  <source type="image/avif" sizes="100vw"          srcset="/img/hero-800.avif 800w,                  /img/hero-1200.avif 1200w,                  /img/hero-2400.avif 2400w">  <img src="/img/hero-1200.jpg" alt="Laptop sale"       width="2400" height="1200" fetchpriority="high"       srcset="/img/hero-800.jpg 800w,               /img/hero-1200.jpg 1200w,               /img/hero-2400.jpg 2400w"       sizes="100vw"></picture>

A 390 px wide phone with DPR 3 takes the 1200w variant: a quarter of the pixels of the 2,400 px one, and in AVIF rather than JPEG. Loading starts with high priority, and the space for the banner is reserved from width and height, so the text does not move.

Section sources

the section is written from these pages

Web fonts

The browser downloads a web font only when the page’s styles use it, and by default hides the text until it has loaded. So a font delays FCP and LCP, and swapping a fallback font for a web font shifts lines and hurts CLS.

@font-face itself does not start the download: the file is requested when the page has an element with that font-family. If @font-face sits in an external CSS file, the font is discovered even later, after the styles have loaded. There are two ways to speed up discovery: inline @font-face in the head or preload the file.

font-display: what to show before the font loads

The font-display descriptor in @font-face defines two periods. During the block period, text is drawn in an invisible fallback font. During the swap period, text is visible in the fallback font and changes to the web font as soon as it loads.

ValueBlockSwapWhen to choose it
autobrowser decidesbrowser decidesthe default
block2–3 sunlimitedthe text must be set only in the web font
swapalmost noneunlimitedheadings and a brand font: the text is visible at once
fallbackabout 100 msabout 3 sa compromise between block and swap
optionalabout 100 msnonebody text: no shifts from swapping

By default, Chromium and Firefox hide text for up to 3 s, and Safari until the font has loaded. With optional, the web font is used only if it arrives within 100 ms; otherwise the page stays on the fallback, and the font finishes downloading into the cache for later navigations. Combine them: swap for the brand and headings, optional for body text.

WOFF2 and subsets

Serve only WOFF2: it is compressed with Brotli, is 30% better than WOFF, and is supported by all modern browsers. A subset is a file with only the glyphs you need. The unicode-range descriptor says which characters a file is for: the browser downloads it only if the page contains such characters. This is how separate files are served for Latin and Cyrillic.

cssstyles.css
/* Latin: basic characters */@font-face {  font-family: "Inter";  src: url("/fonts/inter-latin.woff2") format("woff2");  font-display: swap;  unicode-range: U+0000-00FF;}/* Latin Extended: including ğ and ş */@font-face {  font-family: "Inter";  src: url("/fonts/inter-latin-ext.woff2") format("woff2");  font-display: swap;  unicode-range: U+0100-024F;}

Uzbek text in the new alphabet needs both files: ö and ç are within the first 256 Unicode characters, but ğ (U+011F) and ş (U+015F) are already in Latin Extended. If you serve only the basic subset, these letters are drawn in the fallback font.

Preloading and third-party services

Preload only the most important fonts, those used on the first screen, and in a single format. The crossorigin attribute is required even for a font from your own domain: fonts are loaded with CORS. Preloading ignores unicode-range and takes bandwidth from other resources, so preloading every font style is harmful.

htmlin <head>
<link rel="preload" href="/fonts/inter-latin.woff2" as="font"      type="font/woff2" crossorigin>

A font from a third-party service requires connections to its domains; Google Fonts has two: fonts.googleapis.com for CSS and fonts.gstatic.com for the files, the second with crossorigin. A preconnect to both shortens the wait. Self-hosting removes these connections, but the gain is noticeable with a CDN and HTTP/2; you then prepare the subsets and WOFF2 yourself.

A fallback font without shifts

So that the swap does not move lines, the fallback font is tuned to the web font’s metrics. The size-adjust descriptor scales the glyphs of the local font, while ascent-override, descent-override and line-gap-override adjust the height above the line, below the line and the line gap. In this example, headings are set in the Brand font with swap, and before it loads they use Arial adjusted to match Brand.

cssstyles.css
@font-face {  font-family: "Brand";  src: url("/fonts/brand.woff2") format("woff2");  font-display: swap;}/* Arial adjusted to Brand’s metrics */@font-face {  font-family: "Brand Fallback";  src: local("Arial");  size-adjust: 104%;  ascent-override: 92%;}h1, h2 {  font-family: "Brand", "Brand Fallback", sans-serif;}

Tune the values for your own pair of fonts: change them until a heading in the fallback font takes up the same space as in the web font. Always specify a generic fallback such as sans-serif: without it Chrome falls back to Times, which fits worse. For body text you can avoid loading anything at all with font-family: system-ui.

Section sources

the section is written from these pages

JavaScript and long tasks

A long task is main-thread work that lasts longer than 50 ms; while it runs, the browser cannot respond to a click or draw a frame. That is where poor INP comes from. The cure is to break tasks up, load less JavaScript at startup and move heavy computation into a Web Worker.

The main thread runs almost all of a page’s JavaScript, parses HTML and CSS and computes layout, one task at a time. A downloaded script still has to be parsed, compiled and executed, and all of that is main-thread work. Lighthouse warns if JavaScript execution takes more than 2 seconds and fails the audit after 3.5 seconds. Work at load time is especially costly: TBT is strongly related to INP, because people often try to tap while the page is loading.

A single 300 ms task does not let a click start until it finishes. If the same work is split into parts and the thread is handed back to the browser between them (yield), the click handler runs in the nearest gap, and the rest of the work continues after it.

How to yield to the main thread

Functions called inside one function run as a single task. setTimeout(fn, 0) moves the work into a new task, but at the end of the queue, and after five nested calls the browser adds a delay of at least 5 ms. scheduler.yield() returns a promise that resolves in the next task, and the rest of the function runs ahead of other tasks of the same priority. It is available in Chrome, Edge and Firefox but not yet in Safari, so you need a fallback.

javascriptapp.js
function yieldToMain() {  if (globalThis.scheduler?.yield) {    return scheduler.yield();  }  // fallback for browsers without scheduler.yield  return new Promise((resolve) => setTimeout(resolve, 0));} async function saveSettings() {  // what the user must see right away  validateForm();  showSpinner();  updateUI();  await yieldToMain();  // the rest runs in the next task  saveToDatabase();  sendAnalytics();}

Yielding after every small step is expensive: yield has its own cost. Group the work in a loop and yield only if more than 50 ms have passed since the last time. Do not use isInputPending() for this: it can wrongly report that there is no input, and you need to yield not only to input but also to rendering.

A worked example: a 300 ms search

A search field filters 10,000 products on every keystroke, and one filtering pass takes about 300 ms. While it runs, characters appear with a delay, and the page’s INP is over 300 ms.

javascriptdon’t do this
input.addEventListener('input', () => {  // filtering all products is a single 300 ms task  const found = products.filter((p) => matches(p, input.value));  renderResults(found);});
javascriptdo this
input.addEventListener('input', async () => {  const query = input.value;  // the browser has time to show the typed character  await yieldToMain();  const found = [];  let lastYield = performance.now();  for (const product of products) {    if (matches(product, query)) found.push(product);    if (performance.now() - lastYield > 50) {      await yieldToMain();      // the query has changed: this work is no longer needed      if (input.value !== query) return;      lastYield = performance.now();    }  }  renderResults(found);});

Now the frame with the new character is drawn at once, filtering runs in chunks of no more than 50 ms, and an outdated search is abandoned on the next keystroke. The interaction waits only for the first part of the work, not for the whole filtering pass.

Less JavaScript at startup

Code splitting keeps only what the page needs for its first work in the initial bundle and loads the rest later, with dynamic import() by route and by action. Webpack, Parcel and Rollup split the build at import() on their own; esbuild does so only if you enable it. The Coverage tab in DevTools shows unused code. For a large module tree there is the modulepreload hint, but built bundles still load faster than a scatter of modules.

javascriptapp.js
const form = document.querySelector('#signup'); form.addEventListener('focusin', async () => {  // the validation module downloads on the first focus on the form  const { validateForm } = await import('/js/validate-form.mjs');  validateForm(form);}, { once: true });

Third-party scripts

  • Remove a script if it brings no clear benefit to the site.
  • Include third-party scripts with async or defer if they do not need to run before rendering.
  • Open a connection to important third-party origins in advance (preconnect): this saves 100–500 ms.
  • Load ads and embeds below the first screen lazily, after the main content.
  • Self-hosting a third-party script gives you control over caching, but the script no longer updates itself, including security fixes.

Web Workers for heavy computation

A Web Worker runs JavaScript in a separate thread and does not occupy the main one. It has no access to the DOM: it receives and returns data through postMessage messages, while fetch and many other APIs are available to it. It suits parsing large data, compression and calculations after which you only need to show the result.

javascriptapp.js
const worker = new Worker('/js/search-worker.js'); worker.addEventListener('message', ({ data }) => {  renderResults(data);}); worker.postMessage({ query: 'laptop' });
javascriptsearch-worker.js
self.addEventListener('message', ({ data }) => {  // the heavy calculation runs off the main thread  const found = searchIndex(data.query);  self.postMessage(found);});

The Performance panel in DevTools helps find the guilty task: long tasks are marked with a red triangle, and the part over 50 ms is hatched. For tasks that share a frame with rendering, there is the Long Animation Frames API (LoAF): it provides long-animation-frame entries with each script’s contribution through a PerformanceObserver; for now it works only in Chromium. How the event loop works in JavaScript is covered in the JavaScript reference, in the section “Asynchrony: promises, async and the event loop”.

Section sources

the section is written from these pages

Caching for speed

The fastest resource is one you never have to download. For speed, configure the cache like this: files with a hash in the name are stored for a year, HTML is checked with the server every time, and the page stays eligible for the back/forward cache (bfcache), so the Back button works instantly.

A request passes through the layers in order. First comes the service worker, if one is registered and intercepts requests with a fetch handler. Then the browser’s HTTP cache, which keeps responses in memory and on disk: a fresh response is served from there without touching the network. After that the request goes out to the network, to the CDN and, on a miss, to the application server. Every layer that answers on its own removes the latency of all the layers after it. The back/forward cache is separate: it returns the whole page from memory without a single request.

The earlier a layer answers, the lower the TTFB and the resource load time.

Headers: hashed files and HTML

What you serveCache-ControlWhy
files with a hash or version in the name: app.3f9a1c.js, main.8c2e41.cssmax-age=31536000, immutablethe URL changes when the file does; a year is the longest allowed lifetime
HTML pageno-cache and ETagchecked with the server every time; if unchanged, the response is 304
page after sign-inno-cache, privatestays out of shared caches such as a CDN
response with secret datano-storeis not stored anywhere, but makes the page ineligible for the bfcache, so use it only where you must
httpresponse for app.3f9a1c.js
HTTP/1.1 200 OKContent-Type: text/javascriptCache-Control: max-age=31536000, immutableETag: "3f9a1c"
httpresponse for index.html
HTTP/1.1 200 OKContent-Type: text/htmlCache-Control: no-cacheETag: "AAPuIbAOdvAG"

immutable removes revalidation when the page is reloaded; Firefox and Safari support the directive, Chromium does not. A response without Cache-Control is still cached, heuristically, for roughly a tenth of the time since Last-Modified, so set the header explicitly. The meaning of the directives and conditional requests is covered in the “HTTP and REST” reference, in the “Caching” section; server-side setup is in the Nginx reference, in the “Caching and compression” section.

CDN

A CDN (content delivery network) is a network of servers close to users: packets travel a shorter path, the connection is opened near the person, and the cache on the edge server answers without a trip to the origin. Keep versioned static files in the CDN for 6 months or a year. Even frequently changing responses are worth caching for a few seconds at peak times, for example 5 s. A good target is a 90% cache hit ratio. Hits are spoiled by extra parameters such as ?referral_id=, a different parameter order and Set-Cookie in the response. Compress text responses with Brotli, or gzip if Brotli is not available.

Back/forward cache (bfcache)

The back/forward cache (bfcache) keeps a snapshot of the whole page in memory, including the JavaScript state, and shows it without the network when the user clicks Back or Forward. One in ten navigations on desktop and one in five on mobile are exactly that. The bfcache exists in all major browsers, but a page may fail to enter it. The most common blockers are:

  • an unload handler: use pagehide instead; you can disable unload for all scripts on the page with the Permissions-Policy: unload=() header
  • Cache-Control: no-store on the page itself
  • an open IndexedDB connection, an unfinished fetch or XHR, WebSocket and WebRTC: close them in pagehide and reopen them in pageshow
  • a window.opener reference to a window opened with window.open()
  • a beforeunload handler that is always added, instead of only when there are unsaved changes
javascriptapp.js
window.addEventListener('pageshow', (event) => {  if (event.persisted) {    // restored from the bfcache: refresh the cart and counters    refreshCart();  }});

To test a page, open DevTools → Application → Back-forward Cache → “Run Test”. If the page was not restored, the panel names the reason and marks those that can be fixed in code. The NotRestoredReasons API reports the reason for a failure in the field.

Service worker

A service worker intercepts the page’s requests and decides for itself whether to answer from its own cache or from the network. This is something the HTTP cache cannot do: answering on an unreliable network, working offline and precise control over what is stored. Entries can be kept longer than the max-age of the HTTP cache. Files needed offline, such as the app shell and an offline page, are placed in the cache in advance, when the service worker is installed: this is precaching. You do not have to write strategies from scratch; the Workbox library provides them.

StrategyWhen it fits
Network onlydata that must always be fresh: payment, balance
Network, falling back to cachefresh is better but stale is acceptable: prices, order statuses
stale-while-revalidateserve from the cache straight away and update in the background: news feeds, catalogues
Cache, falling back to networknon-critical content that rarely updates: the app shell
Cache onlythings that almost never change: static files

Section sources

the section is written from these pages

Common mistakes in approach

Speed is usually lost not to complex problems but to default decisions: lazy loading on every image, no dimensions, testing on a fast laptop, optimising once. Each of these mistakes shows up in field data and can be caught in CI.

Chasing the Lighthouse score

The Lighthouse score is a weighted average of lab metrics from a single run, and it fluctuates because of ads, A/B tests, the network and the device. A team pushes it to 100, yet users’ LCP and INP do not change: the score has no INP, no slow phones and no repeat visits.

The goal is field Core Web Vitals at the 75th percentile; Lighthouse is a diagnostic tool. Example: the score rose from 70 to 95 because the test environment has no ads, but in the field LCP is still 3.4 s, so what needs fixing is the ads and the loading order on the real site.

Lazy-loading the LCP image

The template adds loading="lazy" to every img, so the first-screen banner waits too: the browser starts loading it only after layout, once it has confirmed that the image is visible. Resource load delay grows, and LCP with it.

Remove loading="lazy" from first-screen images and give the LCP image fetchpriority="high"; lazy-load only what is below. In a catalogue the first cards are usually visible immediately and do not need the attribute.

Testing only on a fast computer

On a work laptop with a good network everything flies, while visitors with budget phones and slow networks see a different page. Aggregate figures across all devices hide the problem: phones and desktops can land in different zones.

Look at phones and desktops separately: PageSpeed Insights shows them separately, both for a URL and for the whole origin. Calculate the budget from your visitors’ devices and networks, for example a budget Android phone on 3G, not from your own computer.

Preload and high priority for everything

When preload and fetchpriority="high" are set on a dozen resources, they once again compete for one channel and the LCP image loses its advantage. High priority stops helping beyond one or two images.

Preload only what the browser discovers late and what the first screen cannot do without: a font, a CSS background, a resource requested from JavaScript. Give high priority to the LCP image and low priority to hidden carousel slides. Check priorities in DevTools on the Network tab.

Images and embeds without dimensions

An image, ad or embed without dimensions is 0 px tall before it loads and then pushes the text apart: the reader loses their place or taps the wrong thing. Ads are one of the main sources of shifts, because their size is often unknown in advance.

Set width and height on images and video, and min-height or aspect-ratio on the space for ads and embeds. If an ad does not arrive, leave a placeholder in its place: a collapsed slot shifts the page just as an appearing one does. Put late content lower on the page.

cssstyles.css
.ad-slot {  /* reserve space for the banner before the ad loads */  min-height: 250px;}

Heavy scripts ahead of content

An A/B testing library hides content while it picks a variant, and third-party scripts occupy the main thread. The image loaded long ago, but the LCP element is not painted: render delay grows, and long tasks hurt INP as well.

Do not hide content until third-party scripts have run, load them with defer or after the page has loaded, and break up long tasks. If client-side JavaScript renders the LCP element, switch to server-side rendering or static generation, so the image is visible in the HTML straight away.

One-off optimisation without a budget

The site was sped up, six months later new libraries and banners undid it all, and the team found out from complaints. A performance budget is a limit that prevents backsliding: on time (LCP, FCP), on size (JavaScript, images) or on a rule (Lighthouse score).

Set two levels: a warning that does not block the release and an error that stops it. Check the budget on every change, for example with Lighthouse CI:

jsonlighthouserc.json
{  "ci": {    "collect": {      "staticDistDir": "./dist",      "numberOfRuns": 3    },    "assert": {      "assertions": {        "largest-contentful-paint": [          "error",          {"maxNumericValue": 2500, "aggregationMethod": "median"}        ],        "cumulative-layout-shift": [          "error",          {"maxNumericValue": 0.1, "aggregationMethod": "median"}        ],        "categories:performance": [          "warn", {"minScore": 0.9}        ]      }    }  }}
bashin CI after the build
lhci autorun

lhci autorun makes three runs and fails if the median LCP is above 2.5 s or the median CLS is above 0.1; a score below 90 gives only a warning. The CI budget catches a regression before release, and field data shows whether the result held up for users.

Section sources

the section is written from these pages

Standards and their status

Core Web Vitals is a Google programme: its set of metrics and thresholds (LCP up to 2.5 s, INP up to 200 ms, CLS up to 0.1 at the 75th percentile) are not standardised by the W3C. The measurements themselves are described by specifications from the W3C Web Performance Working Group, and layout shifts for CLS by a WICG community draft.

Stable Core Web Vitals metrics change no more than once a year and with advance notice; new metrics go through the experimental and pending stages. That is why this section is checked against both specification statuses and the Web Vitals page.

DocumentWhat it definesStatusReplaced or supplemented by
Web Vitals (Core Web Vitals)the set of metrics and thresholdsGoogle programme; LCP, INP and CLS are stableINP replaced FID in March 2024
Largest Contentful PaintAPI for the largest element paint, LCPW3C Working Draft, 26 August 2026—
Event Timing APIdelays of events caused by user actionsWorking Draft, 13 October 2026—
Layout Instability APIlayout shifts and the definition of CLSWICG Draft Community Group Report, 6 November 2026; not on the W3C standards track—
Paint TimingFirst Paint and FCPWorking Draft, 14 October 2026—
Navigation Timing Level 2document navigation timingsWorking Draft, 2 November 2026replaces Navigation Timing (Recommendation, 17 December 2012)
Resource Timingload timings of the page’s resourcesCandidate Recommendation Draft, 2 November 2026Resource Timing Level 1 is marked as Superseded
Performance Timelinecommon access to performance entriesCandidate Recommendation Draft, 21 May 2025first version: Recommendation, 12 December 2013
Server Timingserver metrics in the response: the Server-Timing headerWorking Draft, 2 November 2026—
Long Animation Frames APIlong frames that occupy the main thread for a long timeFirst Public Working Draft, 28 April 2026—
Preload, Resource Hintsseparate resource hint specificationsRetired—

What changed in recent editions

  • INP became a stable Core Web Vitals metric in place of FID in March 2024; Chrome tools supported FID until 9 September 2024.
  • The Long Animation Frames API was published as a First Public Working Draft on 28 April 2026.
  • Between August and November 2026, new editions of Largest Contentful Paint, Navigation Timing Level 2, Event Timing, Paint Timing and Server Timing were published, and Resource Timing got a new Candidate Recommendation Draft.
  • The working group retired the Preload and Resource Hints specifications as separate documents.

Outdated documents that are still quoted

FID (First Input Delay) is no longer part of Core Web Vitals: assessments and reports that measure responsiveness by FID are out of date. TTI (Time to Interactive) was a lab metric: Lighthouse no longer includes it in the score, and it is not measured in the field; Core Web Vitals use INP instead. Level 2 of Navigation Timing keeps the first version of Navigation Timing and the PerformanceTiming interface (performance.timing) only for compatibility and advises against using them; use PerformanceNavigationTiming entries from performance.getEntriesByType('navigation') instead.

Section sources

the section is written from these pages

End of the reference

What changed

revision history · 3 entries

Every edit is saved as a revision: a snapshot of the reference, the reason and a summary of changes. The published version changes only after the same checks as at creation.

  1. Manual edit

    reason: manual edit
  2. Manual edit

    reason: manual edit
  3. Reference updated

Weekly check

How the reference is checked

Once a week — and right after news of a release or a vulnerability — the reference is checked in three steps.

  1. 1. Freshness

    Sections are compared with the release notes and changelogs from the official sources and with the topic’s news.

  2. 2. Errors

    Every section is read again: wrong facts, outdated APIs and flags, broken examples.

  3. 3. Links — by an HTTP request

    Every source link must respond. A broken link is a reason to recheck the section.

No findings — only the date changes. Findings — only the affected sections are rewritten, and they appear in “What changed”. A new version replaces the published one only after passing the same checks as at creation.

Statuses

Verified
no findings
Updated
sections rewritten, edits are listed
Rechecking
while the check runs, the previous version stays open
Needs review
disputed points: the verified version is shown, editors review

Last check

10 Nov · Check · updated · no findings

Found an error in the reference?

On the topic

tracks, news and other references
The whole “Web performance” topic
13 sections
Another reference · Backend

HTTP and REST

Verified 1 Nov
All references · 61