Web Performance Basics
What makes a page feel slow, and the basic techniques for making it fast.
What is it?
Most slowness comes from the browser being busy or waiting before it can show or use something:
- A stylesheet or script that must download and run before anything shows is render-blocking. The page stays blank while the browser waits.
- Large, unoptimized images take a long time to download, delaying everything that depends on them.
- Lots of JavaScript still has to be parsed and run after downloading, so a page can look finished but not respond to clicks and taps.
A few well-known techniques address these:
- Lazy loading waits to fetch something (like an image far down the page) until it's about to be needed.
- Minification strips unneeded characters (whitespace, long variable names) from CSS and JavaScript, so less data is sent.
- Caching lets the browser reuse a file from an earlier visit instead of downloading it again when it hasn't changed.
Explain like I'm 10
It's like being handed a phone book at a restaurant door when all you wanted was the menu. Render-blocking resources make you wait through unrelated work before you get what you came for.
Examples
Avoiding render-blocking scripts
<!-- Blocks rendering until fully downloaded and run -->
<script src="analytics.js"></script>
<!-- Downloads in the background, runs after parsing finishes -->
<script src="analytics.js" defer></script>Without defer, the browser stops parsing the HTML to fetch and run the script right away. With defer, the script downloads in parallel and runs after parsing finishes, so it doesn't delay the visible page.
Lazy loading images
<img src="hero.jpg" alt="Product hero image">
<img src="footer-banner.jpg" alt="Seasonal promotion" loading="lazy">The hero image loads right away because it's visible immediately. The footer banner is probably far below the first screen, so loading="lazy" tells the browser to fetch it only when the user scrolls near it.
How it works
Parsing HTML, downloading files, running CSS and JavaScript, and rendering all compete for the browser's time. Deferring scripts, lazy loading offscreen images, and minifying files reduce or reschedule that work: less data over the network, or less waiting before something useful appears.
Caching works differently. It skips the network entirely for files the browser already has an unchanged copy of.
Why does it exist?
A slow page costs user attention and, for businesses, measurable results: people abandon slow pages far more often. As pages have grown heavier (more images, scripts, and third-party embeds), these techniques have become necessary to keep pages usable, not optional polish.
When to use it
Use these by default on any real website: defer non-critical scripts, lazy-load offscreen images, minify production CSS and JavaScript, and set caching headers on assets that rarely change. Look closer when users report slowness or when measured load times show a problem.
When not to use it
Very small or low-traffic internal tools may not need heavy tuning. For example, setting up a build pipeline just for minification may not pay off if load time is already unnoticeable. Optimizing before you know where the time goes can also waste effort on the wrong thing.
Common mistakes
Loading large, unoptimized images at full resolution when a much smaller version would look the same on screen.
Lazy-loading a critical, above-the-fold image, which delays content the user sees right away.
Expecting minification to fix a problem caused by shipping too much JavaScript in the first place.
Practice exercises
- Easy:
Add the loading="lazy" attribute to images below the visible area on a sample page.
- Medium:
Change a blocking <script> tag in a page's head to use defer, then explain how page loading changes.
- Hard:
In your browser's Network panel, measure a real page's load time, find the largest resource slowing it down, and propose one concrete fix.
Interview questions
What does 'render-blocking' mean?
A resource, like a script or stylesheet, that the browser must fully download (and sometimes run) before it can keep rendering, causing a visible delay.
What is lazy loading, and when is it appropriate?
Waiting to load a resource, usually an image, until it's about to be needed, such as when it scrolls near the viewport. Use it for offscreen content, not for content visible as soon as the page loads.
How does caching improve web performance?
The browser reuses a file it already downloaded instead of fetching it again, as long as it hasn't changed. That saves time and bandwidth on repeat visits.
What are the Core Web Vitals, and which three metrics make up the current set?
Metrics Google uses to measure real-world user experience: Largest Contentful Paint (LCP, loading speed), Interaction to Next Paint (INP, responsiveness), and Cumulative Layout Shift (CLS, visual stability).
What does Largest Contentful Paint (LCP) measure, and what's considered a good score?
How long the largest visible content element (often a hero image or big block of text) takes to finish rendering after the page starts loading. 2.5 seconds or less is generally considered good.
What does Cumulative Layout Shift (CLS) measure, and what commonly causes a poor score?
How much visible content unexpectedly moves during load, weighted by how much of the viewport moved and how far. Common causes: images or embeds with no reserved width/height, content (like an ad or banner) injected above existing content after load, and web fonts swapping in with different metrics than the fallback.
What replaced First Input Delay (FID) as a Core Web Vital, and why?
Interaction to Next Paint (INP). FID only measured the delay before the first interaction began processing, missing problems later on. INP measures responsiveness across every interaction during the page's life, giving a fuller picture.
What are the main stages of the critical rendering path?
Parse HTML into a DOM, parse CSS into a CSSOM, combine them into a render tree of visible nodes with computed styles, calculate each node's position and size (layout), then paint pixels to the screen.
Why is CSS treated as render-blocking by default?
The browser waits for the full CSSOM before rendering so it doesn't paint unstyled content and then repaint it when styles arrive. That jarring flash of unstyled content (FOUC) is avoided by holding the first paint until styling is known.
What's the tradeoff between putting a `<link rel="stylesheet">` in the `<head>` versus at the end of `<body>`?
In the head, rendering waits for the CSS, so first paint is later but the page never appears unstyled. At the end of the body, the browser may briefly paint unstyled content, then reflow everything when the CSS loads. Something shows sooner, but it usually looks worse.
What's the difference between `async` and `defer` on a `<script>` tag?
Both download without blocking parsing. async runs the script as soon as it downloads, which can interrupt parsing and doesn't guarantee order among scripts. defer waits until the HTML is fully parsed, and deferred scripts always run in document order. That makes defer the safer default for scripts that depend on the DOM or on each other.
Why is reflow (layout) generally more expensive than repaint?
A repaint redraws pixels whose appearance changed (like a color) without touching geometry. A reflow recalculates the size and position of the changed element and possibly every element it affects, which can cascade across much of the page.
What is 'layout thrashing', and what's a common way it happens by accident?
Code forcing the browser to recalculate layout synchronously many times in a tight loop instead of once. The classic cause is reading a layout property (like element.offsetHeight) right after a style change inside a loop: each read forces the browser to flush and recompute layout before answering.
Why can overusing `will-change` hurt performance instead of helping it?
will-change hints that the browser should promote an element to its own compositing layer ahead of an animation. Using it broadly, or on elements that don't need it, creates many extra layers that use more GPU memory and can slow things down.
When would you still need an Intersection Observer-based lazy-loading approach instead of native `loading="lazy"`?
When you need more control than the default: lazy-loading something other than images/iframes (e.g. a heavy component), choosing how early loading starts, or supporting older browsers without the loading attribute.
What is code splitting, and how does it help a large JavaScript application load faster?
It splits one large bundle into smaller chunks loaded on demand, for example per route. A first visit then downloads and parses only the code for the current page, not the whole app.
What does tree shaking remove from a JavaScript bundle?
Dead code: module exports that are never imported or used. It works by static analysis of import/export statements, so the bundle leaves out library code the app never calls.
What's the difference between `<link rel="preload">`, `rel="prefetch"`, and `rel="preconnect"`?
preload fetches a resource the current page definitely needs, at high priority, before the browser would find it on its own. prefetch fetches something a future navigation probably needs, at low priority. preconnect only sets up the connection (DNS, TCP, TLS) to another origin in advance, without fetching a file, to save that time later.
Your page's LCP element is a large hero image loading late. Name two concrete ways to improve it.
Preload it with <link rel="preload" as="image"> so the browser fetches it early instead of finding it only when parsing reaches the img tag. And serve a properly sized, modern-format file (e.g. WebP/AVIF) so there's less to download.
Does minifying JavaScript reduce how long the browser takes to execute it?
Not meaningfully. Minification makes the file smaller (less to download and parse), but the logic runs the same operations, so execution time stays about the same. That's why it can't fix shipping too much JavaScript.
What is `font-display: swap`, and what performance/visual tradeoff does it introduce?
It shows text right away in a fallback font while the web font downloads, then swaps to the real font, so text is never invisible. The tradeoff: if the two fonts have different metrics (character widths, line height), the swap can shift the layout and hurt CLS.
Why does compressing assets with gzip or Brotli improve load performance, and which one usually compresses better?
Both shrink the bytes sent for text assets like HTML, CSS, and JS, so they download faster. Brotli usually compresses better than gzip, though it can take a bit longer to compress. That affects build time more than serving an already-compressed file.
How did HTTP/2 multiplexing reduce the value of older performance tricks like bundling many files together or sharding assets across multiple domains?
HTTP/1.1 allowed only a few parallel requests per connection, so bundling (fewer requests) and domain sharding (more connections) worked around the limit. HTTP/2 sends many requests over one connection at once, removing much of that overhead. Bundling everything into one giant file can now hurt caching without the old payoff.
Using browser DevTools, how would you tell whether a slow page load is bottlenecked by network transfer or by JavaScript execution?
The Network panel's waterfall shows how long each resource spent downloading versus waiting; large or slow requests point to the network. The Performance panel's main-thread flame chart shows time spent parsing, compiling, and running JavaScript and doing layout/paint; if most time is there, you're CPU-bound.
An `<img>` has no `width`/`height` attributes set. What layout symptom can result once it finishes loading on a slow connection, and how do you prevent it?
Before it loads, the browser doesn't know its size and reserves no space, so other content fills that area. When the image arrives, everything below jumps to make room, a layout shift that counts against CLS. Set width/height attributes (or CSS aspect-ratio) so the browser reserves the space before the image even starts downloading.
What's the Core Web Vitals tradeoff between client-side rendering (CSR) and server-side rendering (SSR)?
SSR usually gives better LCP/FCP on first load, since the HTML arrives with real content instead of an empty shell waiting for JavaScript to fetch and render data. CSR is often slower on first load for that reason, but can feel faster on later in-app navigations, once the bundle is loaded and only data needs fetching.
What does Time to First Byte (TTFB) measure, and what does a slow TTFB usually indicate?
The time from sending a request to receiving the first byte of the response. It mostly reflects server-side work (routing, database queries, server-side rendering), not front-end asset delivery. A slow TTFB points to a backend or network-latency problem that minification or lazy loading can't fix.
Mechanically, how does a CDN improve load performance?
It caches static assets on servers spread out geographically, close to users. Requests are served from a nearby edge location instead of a distant origin server, cutting round-trip time.
A returning visitor loads a page much faster than a first-time visitor loading the exact same assets. What's the likely mechanism, given proper `Cache-Control` headers?
The browser's disk/memory cache already holds the CSS, JS, and images from the last visit, and Cache-Control headers (e.g. a max-age) say they're still valid. So it uses them from cache without any network request. A first-time visitor has no cache and downloads everything.
What's a common pitfall of giving a file like `app.js` a very long `Cache-Control: max-age`?
After a new deploy, users with a cached copy keep the old file until the cache expires, possibly running outdated code (or broken code, if the backend changed) for a long time. The standard fix is a content hash in the filename (e.g. app.3f2a1c.js). Each deploy produces a new filename that's fetched fresh, and the long cache is safe because a given filename's content never changes.