PrepStack › Frontend › Browser & Web Performance
Browser & Web Performance interview cheat sheet
Rendering pipeline, Core Web Vitals, loading, caching and runtime speed
Senior frontend rounds almost always include a performance block. Interviewers check that you know how the browser turns bytes into pixels, what blocks rendering, how Core Web Vitals (LCP, INP, CLS) are measured, and which fix matches which problem: caching, code splitting, image work, or freeing the main thread. Expect open questions like “this page is slow, what do you do?”. Revise the 15-minute list first, then use Quiz mode and answer out loud with a measure → find bottleneck → fix → verify structure.
15-minute revision
- Pipeline: HTML → DOM, CSS → CSSOM, DOM + CSSOM → render tree → layout (geometry) → paint (pixels into layers) → composite (GPU combines layers).
- CSS is render-blocking. A plain
<script>is parser-blocking.deferruns after parsing in order;asyncruns as soon as it downloads, in any order. - Changing geometry (width, top, font-size) triggers reflow + repaint + composite. Colour changes trigger repaint.
transformandopacitycan be composite-only. - Layout thrashing = alternating DOM writes and layout reads (
offsetHeight) in a loop. Fix: batch all reads, then all writes. - Core Web Vitals (good at p75): LCP ≤ 2.5 s, INP ≤ 200 ms, CLS ≤ 0.1. Poor: LCP > 4 s, INP > 500 ms, CLS > 0.25.
- INP replaced FID as a Core Web Vital in March 2024. FID measured only the first input's delay; INP covers the full latency of almost all interactions.
- Lab data (Lighthouse, DevTools) is for debugging. Field data (RUM, CrUX) is what users feel and what Google ranks on.
- A long task is any main-thread task over 50 ms. Break it up, yield to the browser, or move work to a Web Worker.
- Resource hints:
preconnect= open the connection early,preload= fetch this resource now for the current page,prefetch= low-priority fetch for a likely next page. - Cut JS: code splitting with dynamic
import(), tree shaking of unused ESM exports, minify, and compress with Brotli or gzip. - Images: use AVIF/WebP, responsive
srcset/sizes, setwidth/heightto avoid CLS,loading="lazy"below the fold, never lazy-load the LCP image. - Caching: hashed static files get
Cache-Control: public, max-age=31536000, immutable. HTML getsno-cacheplus an ETag so it revalidates (304). no-cachemeans “revalidate before using”;no-storemeans “never store”. ETag +If-None-Matchgives a cheap 304 Not Modified.- HTTP/2 multiplexes streams over one TCP connection. HTTP/3 runs over QUIC (UDP) and removes TCP head-of-line blocking.
- Rendering patterns: CSR (JS builds the page), SSR (HTML per request), SSG (HTML at build), hydration attaches JS to server HTML, islands hydrate only interactive parts.
- Common memory leaks: listeners and timers never removed, detached DOM nodes still referenced, growing caches and global maps, closures holding big objects.
How the browser renders
What happens when you type a URL (frontend view)
Resolve, connect, fetch HTML, parse it while discovering sub-resources, build DOM and CSSOM, then layout, paint and composite.
- Navigation: the browser process parses the input (URL or search), checks the bfcache / HTTP cache, then resolves DNS to an IP.
- Connection: TCP handshake plus TLS handshake for HTTPS (HTTP/3 merges both into QUIC). Each round trip costs latency, which is why
preconnecthelps. - Request/response: the server returns HTML. The time until the first byte arrives is TTFB. Redirects add full extra round trips.
- Parsing: the HTML parser builds the DOM incrementally. A preload scanner looks ahead and starts fetching CSS, JS and images early.
- Rendering: DOM + CSSOM → render tree → layout → paint → composite. First paint happens once render-blocking CSS is ready.
- After load: JS runs, the page becomes interactive, more data is fetched. Metrics along the way: TTFB → FCP → LCP, and INP during the whole visit.
Interview questions
- What happens when you type a URL and press Enter? (frontend angle)
- What is TTFB and what affects it?
- What is the preload scanner?
Browser architecture: processes & threads
Modern browsers are multi-process. Each site's renderer has one main thread for JS, style, layout and paint, plus a compositor thread that can scroll and animate on its own.
- Browser process: UI, tabs, navigation, storage and network coordination. GPU process: draws to the screen. Network and other utility processes run as services.
- Renderer process (one per site, thanks to site isolation): runs Blink (DOM, CSS, layout, paint) and V8 (JavaScript). It is sandboxed for security.
- The renderer's main thread does JS, style calculation, layout, paint recording and handling input events. Only one of these runs at a time.
- The compositor thread takes painted layers, splits them into tiles, rasterises them (via raster threads/GPU) and builds frames. It can handle scroll and
transform/opacityanimations without the main thread. - If the main thread is busy for 300 ms, clicks and
requestAnimationFramewait 300 ms. That is the root cause of poor INP and janky animations. - Workers (Web, Service, Shared) run on separate threads and have no DOM access.
Interview questions
- Why do browsers use multiple processes?
- What runs on the main thread vs the compositor thread?
- Why can a long JavaScript task make a button feel broken?
Critical rendering path
The steps from HTML and CSS bytes to the first pixels: DOM, CSSOM, render tree, layout, paint, composite.
- DOM: bytes → characters → tokens → nodes → tree. It is built incrementally as HTML streams in.
- CSSOM: the same process for CSS. It is not incremental for rendering, because later rules can override earlier ones, so the browser waits for the whole stylesheet.
- Render tree: only visible nodes with computed styles.
display: noneelements are excluded;visibility: hiddenones are included (they take space). - Layout (reflow): computes the exact size and position of every box from the viewport down.
- Paint: records draw commands (text, colours, borders, shadows) per layer, then rasterises them into pixels.
- Composite: the GPU combines layers in the right order, applying
transformandopacity, to produce the frame. - Optimise the CRP by reducing the number of critical resources, their bytes, and the number of round trips (critical path length).
Interview questions
- Explain the critical rendering path.
- Difference between DOM and render tree?
- Why is the CSSOM not built incrementally like the DOM?
- What is FOUC?
Render-blocking & parser-blocking resources
CSS blocks rendering; classic scripts block parsing. Use defer, async, type="module" and media queries to unblock.
- Render-blocking: stylesheets in
<head>stop the first paint until downloaded and parsed. - Parser-blocking: a classic
<script src>pauses HTML parsing to download and run. It also waits for preceding CSS, since it may read styles. defer: download in parallel, run after parsing finishes, in document order, beforeDOMContentLoaded.async: download in parallel, run as soon as ready, order not guaranteed. Good for independent scripts like analytics.type="module"scripts are deferred by default; addingasyncmakes them run when ready.- A
<link rel="stylesheet" media="print">is downloaded at low priority and does not block rendering on screen.
Interview questions
- Difference between
asyncanddefer? - Is CSS render-blocking or parser-blocking?
- How would you remove render-blocking resources flagged by Lighthouse?
Reflow vs repaint vs composite & layout thrashing
Geometry changes cost the most (layout), visual-only changes cost less (paint), and transform/opacity can skip both (composite only).
- Reflow (layout): recalculating positions and sizes. Triggered by changing width, height, margin, font-size, content, adding/removing nodes, or resizing the window. Can affect parents, children and siblings.
- Repaint: redrawing pixels without geometry changes, e.g.
color,background,box-shadow,visibility. - Composite only:
transformandopacityon an element with its own layer. The GPU just moves or fades the layer. - Forced synchronous layout: reading
offsetWidth,getBoundingClientRect(),scrollToporgetComputedStyle()after a write makes the browser run layout immediately. - Layout thrashing: doing that read-after-write repeatedly in a loop, causing many layouts per frame.
- Limit scope with CSS
contain: layout paintand skip off-screen work withcontent-visibility: auto.
Interview questions
- Difference between reflow and repaint?
- What is layout thrashing and how do you fix it?
- Why animate
transforminstead ofleft?
JavaScript runtime performance
Long tasks, rAF, idle callbacks & Web Workers
Keep main-thread tasks under 50 ms: split work, yield between chunks, use requestAnimationFrame for visual updates and Workers for heavy computation.
- At 60 Hz a frame is ~16.7 ms. A long task is over 50 ms; it blocks input and painting for that whole time.
- Yielding: split work into chunks and give control back (
setTimeout(…, 0),MessageChannel, orscheduler.yield()where supported) so input can run in between. requestAnimationFrame(cb): runscbright before the next paint. Use it for DOM writes and JS animations. It pauses in background tabs.requestIdleCallback(cb): runs when the browser is idle, with a deadline. Use it for low-priority work like analytics. Not for DOM writes; not supported in older Safari.- Web Workers run JS on another thread and talk via
postMessage(structured clone or transferable objects). No DOM access. - Debounce/throttle event handlers, and avoid heavy work in
scroll/resize/inputhandlers.
Interview questions
- What is a long task and why does it matter?
- Difference between
requestAnimationFrameandsetTimeoutfor animations? - When would you use
requestIdleCallback? - What are the limits of Web Workers?
Debounce, throttle & memoization
Debounce waits until events stop, throttle limits the rate, memoization caches results of pure functions.
- Debounce: run once after the calls stop for
waitms. Use for search-as-you-type, auto-save, resize end. - Throttle: run at most once every
waitms while calls keep coming. Use for scroll position, mouse move, rate-limited APIs. - Memoization: store results by input so repeated calls are free. Only safe for pure functions; bound the cache size.
- In React,
useMemo/useCallback/React.memoare memoization for renders; they add overhead, so use them where profiling shows a need. - For visual updates, throttling with
requestAnimationFrame(one update per frame) is often better than a fixed time interval.
Interview questions
- Difference between debounce and throttle?
- When is memoization a bad idea?
- How would you implement scroll handling efficiently?
List virtualization & DOM size
Render only the rows that are visible (plus a small buffer) so a 100k-row list costs the same as a 20-row list.
- Large DOMs slow down style, layout, memory and every query. Lighthouse warns at roughly 1,400 elements.
- Windowing/virtualization: compute which items fall inside the viewport from
scrollTop, render only those, and use a spacer (ortransform) to keep the total scroll height. - Add an overscan buffer of a few rows above and below so fast scrolling does not show blank space.
- Variable-height rows need measurement and a position cache; fixed heights make the math trivial.
- Libraries: react-window, react-virtual (TanStack Virtual), vue-virtual-scroller. CSS
content-visibility: autois a lighter alternative for long documents. - Trade-offs: browser find-in-page (Ctrl+F) and accessibility tools only see rendered rows.
Interview questions
- How would you render a list of 100,000 items smoothly?
- What are the downsides of virtualization?
- Why is a big DOM slow even if it is not visible?
Memory leaks in the browser
A leak is memory that stays reachable after you stop needing it, usually via forgotten listeners, timers, caches or detached DOM nodes.
- JS uses mark-and-sweep garbage collection: anything reachable from roots (globals, the stack, active closures, the DOM) stays alive.
- Classic leaks: event listeners not removed on unmount, timers/intervals still running, detached DOM nodes still referenced from JS, unbounded caches/maps, accidental globals, closures capturing large objects, uncleaned observers and subscriptions.
- SPAs leak more because pages never fully reload. Every route change must clean up.
- Use
AbortControllerto remove many listeners at once,WeakMap/WeakReffor caches keyed by objects, and cleanup functions inuseEffect. - Diagnose with DevTools Memory: take heap snapshots before and after an action, compare, and look for “Detached” nodes and growing retainers. The Performance monitor shows JS heap and DOM node counts over time.
Interview questions
- What are common causes of memory leaks in a frontend app?
- How do you find a memory leak?
- How does
WeakMaphelp avoid leaks?
Core Web Vitals & measurement
Core Web Vitals: LCP, INP, CLS
Three user-centric metrics for loading (LCP), responsiveness (INP) and visual stability (CLS), judged at the 75th percentile of real users.
- LCP (Largest Contentful Paint): when the largest image or text block in the viewport is rendered. Good ≤ 2.5 s.
- INP (Interaction to Next Paint): latency from a click, tap or key press until the next frame is painted, taken as (roughly) the worst interaction of the visit. Good ≤ 200 ms.
- CLS (Cumulative Layout Shift): a unitless score for unexpected layout movement, using the largest burst (session window) of shifts. Good ≤ 0.1.
- A page passes if all three are “good” at the 75th percentile, measured separately for mobile and desktop.
- INP replaced FID in March 2024. FID only measured the input delay of the first interaction.
- Supporting metrics: TTFB (server/network), FCP (first content), TBT (lab proxy for responsiveness), Speed Index.
Interview questions
- What are Core Web Vitals and their thresholds?
- Why did INP replace FID?
- Why the 75th percentile and not the average?
- What counts as the LCP element?
Fixing LCP, INP & CLS
LCP: get the hero resource early and small. INP: shorten main-thread work around interactions. CLS: reserve space and avoid late-inserted content.
- LCP breakdown: TTFB + resource load delay + resource load time + element render delay. Find which part is large before fixing.
- LCP fixes: make the hero image discoverable in HTML (not lazy, not set by JS), add
fetchpriority="high"orpreload, serve AVIF/WebP sized correctly from a CDN, reduce render-blocking CSS/JS, SSR the hero content. - INP breakdown: input delay (main thread busy) + processing time (your handlers) + presentation delay (style/layout/paint of the next frame).
- INP fixes: break up long tasks and yield, do the minimum in handlers then defer the rest, avoid huge re-renders (memoize, virtualize), reduce DOM size, move work to workers, cut third-party scripts.
- CLS fixes: set
width/heightoraspect-ratioon images, videos and iframes, reserve space for ads/embeds, do not insert banners above existing content, usefont-displaywith metric-matched fallbacks, animate withtransform. - Pages restored from the bfcache load instantly; avoid
unloadlisteners andCache-Control: no-storeon HTML where possible so pages stay eligible.
Interview questions
- Your LCP is 4.5 s on mobile. How do you approach it?
- INP is 450 ms. What do you look for?
- How do you prevent layout shifts?
- What is
fetchpriority?
Measuring: Lighthouse, DevTools, RUM & PerformanceObserver
Use lab tools to debug and field data (RUM) to know what users experience; the Performance APIs feed both.
- Lab data: Lighthouse, PageSpeed Insights (lab part), WebPageTest, DevTools. Controlled device and network, reproducible, great for debugging and CI budgets.
- Field data / RUM: real users on real devices. Sources: CrUX (Chrome UX Report, shown in PageSpeed Insights and Search Console) and your own RUM via the
web-vitalslibrary or a vendor. - DevTools Performance panel: record a trace to see the main thread flame chart, long tasks (red corners), layout/paint events, network waterfall, and live Core Web Vitals.
- Performance APIs: Navigation Timing, Resource Timing, User Timing (
performance.mark/measure), Long Tasks and Long Animation Frames (LoAF), Event Timing, Largest Contentful Paint, Layout Instability. PerformanceObserversubscribes to these entries. Usebuffered: trueto also receive entries recorded before you subscribed.- Set performance budgets (bundle size, LCP) and enforce them in CI with Lighthouse CI or bundler limits.
Interview questions
- Difference between lab data and field data?
- How would you set up Real User Monitoring?
- What is Total Blocking Time (TBT)?
- “Our homepage is slow.” Walk me through how you'd investigate.
- What is a performance budget?
Loading optimizations
Resource hints: preload, prefetch, preconnect
Hints tell the browser about future needs: connect early, fetch critical files now, or fetch likely-next files when idle.
dns-prefetch: resolve DNS for an origin early. Cheap; good fallback for many third-party origins.preconnect: DNS + TCP + TLS early for an origin you will use soon (CDN, font host). Keep it to a few critical origins; unused connections waste resources.preload: fetch a resource needed for this page with high priority, e.g. a hero image, a font referenced deep in CSS. Requires a correctas(andcrossoriginfor fonts).modulepreload: preload an ES module and its parsing, so a laterimportis instant.prefetch: low-priority fetch for a future navigation (next page's JS). Stored in HTTP cache.- Speculation Rules (
<script type="speculationrules">, Chromium) can prefetch or prerender whole next pages for near-instant navigations. 103 Early Hints lets the server send preload/preconnect before the HTML is ready.
Interview questions
- Difference between
preloadandprefetch? - When would you use
preconnect? - What is 103 Early Hints?
Code splitting, tree shaking, minification & compression
Ship less JavaScript: split by route and feature, drop unused code, minify, and compress with Brotli.
- JS is the most expensive byte: it must be downloaded, parsed, compiled and executed on the main thread, unlike an image of the same size.
- Code splitting: break the bundle into chunks loaded on demand with dynamic
import(). Split by route first, then by heavy features (charts, editors, modals).React.lazy+Suspensewrap this in React. - Tree shaking: bundlers (Rollup, webpack, esbuild, Vite) remove exports that are never imported. Needs static ESM and side-effect-free modules (
"sideEffects": falsein package.json). - Minification (Terser, esbuild, SWC) shortens names and removes whitespace and dead code.
- Compression: Brotli (
br) is usually 15–25% smaller than gzip for text. Newer browsers also accept Zstandard (zstd). Pre-compress static assets at build time. - Audit with a bundle analyzer, replace heavy libraries (moment → date-fns/Temporal-ready APIs), and serve modern ES syntax instead of heavy polyfills.
Interview questions
- What is code splitting and how do you do it?
- What is tree shaking and what breaks it?
- Why is 200 KB of JS worse than a 200 KB image?
- gzip vs Brotli?
Images, lazy loading & media
Images are usually the heaviest bytes: pick the right format, size them per device, lazy-load off-screen ones, and always reserve their space.
- Formats: AVIF (best compression, slower to encode) > WebP > JPEG for photos; SVG for icons/logos; PNG only when lossless with transparency is needed. Use
<picture>for fallbacks. - Responsive images:
srcset+sizeslet the browser choose the right resolution for the screen and DPR; never ship a 3000px image to a 400px slot. - Native lazy loading:
loading="lazy"on<img>and<iframe>defers off-screen ones. Do not use it on the LCP/hero image. - IntersectionObserver gives custom lazy loading, infinite scroll and visibility analytics without scroll listeners.
- Set
width/heightattributes (or CSSaspect-ratio) so the browser reserves space and avoids CLS. - Replace GIFs with
<video autoplay muted loop playsinline>; serve images from an image CDN that resizes and converts automatically.
Interview questions
- How do you optimise images on a web page?
- How does native
loading="lazy"differ from IntersectionObserver? - What do
srcsetandsizesdo?
Web font optimization
Fonts can block text rendering and shift layout; serve WOFF2, subset, preload the critical one, and control the swap with font-display.
- Browsers hide text while a web font loads (FOIT, up to ~3 s) unless told otherwise. Swapping fonts late shows FOUT and can cause CLS.
font-display:swap(fallback immediately, swap when loaded),optional(use font only if it arrives very fast; no shift),fallback(short block, short swap),block(long invisible period).- Use WOFF2 only; it is supported everywhere relevant and compresses best.
- Subset with
unicode-rangeand remove unused glyphs; a variable font can replace several weight files. - Preload the one or two fonts used above the fold (with
crossorigin), and self-host orpreconnectto the font CDN. - Reduce shift with metric overrides on the fallback face:
size-adjust,ascent-override,descent-override.
Interview questions
- What are FOIT and FOUT?
- Which
font-displayvalue would you choose? - How do you make fonts load faster?
Network, caching & offline
HTTP caching (Cache-Control, ETag) & CDNs
Cache versioned assets forever and revalidate HTML cheaply; a CDN puts those caches close to users.
Cache-Control: max-age=N: response is fresh for N seconds; no request is made.s-maxageapplies to shared caches (CDN) only.no-cache: may store, but must revalidate with the server before each use.no-store: never store (sensitive data).private: only the browser may cache, not CDNs.immutable: never revalidate while fresh.- Validators:
ETag(content fingerprint) withIf-None-Match, orLast-ModifiedwithIf-Modified-Since. Match → 304 Not Modified with no body. - Cache busting: put a content hash in file names (
app.4f2a.js) and cache them for a year withimmutable. Deploys produce new URLs; HTML points to them. stale-while-revalidate=N: serve a stale copy instantly and refresh in the background.- CDN: edge servers cache static (and sometimes dynamic) content close to users, cutting latency and origin load. Purge or use hashed URLs on deploy; use
Varycarefully (e.g.Accept-Encoding).
Interview questions
- Difference between
no-cacheandno-store? - How do ETags work?
- How do you cache static assets without users getting stale code after a deploy?
- What does a CDN do for performance?
HTTP/1.1 vs HTTP/2 vs HTTP/3
HTTP/2 multiplexes many requests over one connection; HTTP/3 does the same over QUIC/UDP to avoid TCP head-of-line blocking and speed up connection setup.
- HTTP/1.1: one request at a time per connection; browsers open ~6 connections per origin. This led to hacks: bundling, sprites, domain sharding, inlining.
- HTTP/2: binary framing, multiplexed streams on one TCP connection, HPACK header compression, stream prioritisation. Domain sharding becomes harmful.
- HTTP/2 still suffers TCP head-of-line blocking: one lost packet stalls all streams on the connection.
- HTTP/3: runs on QUIC over UDP. Streams are independent at the transport level, TLS 1.3 is built in (1-RTT setup, 0-RTT on resumption), and connections survive network changes (Wi-Fi → mobile) via connection IDs. Header compression is QPACK.
- HTTP/2 server push has been removed from Chrome; use
preloadand 103 Early Hints instead. - Even with HTTP/2+, bundling still helps compression and avoids request overhead, but very fine-grained chunks are now affordable.
Interview questions
- What problems does HTTP/2 solve compared to HTTP/1.1?
- What is head-of-line blocking and how does HTTP/3 fix it?
- Should you still bundle with HTTP/2?
Service workers & PWAs
A service worker is a script that sits between the page and the network, enabling offline support, caching strategies, push and background sync.
- Runs on its own thread, has no DOM access, is event-driven (
install,activate,fetch,push,sync) and requires HTTPS (except localhost). - Lifecycle: register →
install(pre-cache assets) → waiting (old SW still controls tabs) →activate(clean old caches) → controls pages.skipWaiting()andclients.claim()speed up takeover. - Caching strategies: cache-first (hashed static assets), network-first (HTML, API with offline fallback), stale-while-revalidate (avatars, non-critical data), network-only, cache-only.
- Uses the Cache Storage API, which is separate from the HTTP cache and fully controlled by your code.
- A PWA = HTTPS + web app manifest (name, icons,
display,start_url) + service worker. It can be installed and work offline. - Workbox is the common library for strategies, precaching and routing.
Interview questions
- What is a service worker and what can it do?
- Explain the service worker lifecycle.
- Which caching strategy would you use for HTML vs hashed JS?
- What makes a web app a PWA?
Rendering architecture
CSR, SSR, SSG, hydration & islands
Where and when HTML is generated decides TTFB, LCP and INP: on the client, per request on the server, or at build time, plus how much JS hydrates it.
- CSR (client-side rendering): server sends an empty shell + JS bundle; the browser fetches data and renders. Slow first load and LCP, weaker SEO without care, cheap servers, rich app-like navigation.
- SSR (server-side rendering): HTML generated per request. Fast FCP/LCP and good SEO, but higher TTFB and server cost; page needs hydration before it is interactive.
- SSG (static generation): HTML built at build time and served from a CDN. Fastest TTFB; only for content that does not change per user. ISR regenerates pages in the background after a revalidate period.
- Hydration: the client runs the components again to attach event listeners and state to server HTML. Until it finishes, the page looks ready but does not respond: the uncanny valley.
- Streaming SSR: send HTML in chunks (React
Suspense) so the shell paints early and slow parts arrive later. Selective hydration hydrates parts independently, prioritising what the user interacts with. - Islands architecture (Astro, Fresh): mostly static HTML with small interactive islands hydrated independently. React Server Components keep server-only components out of the client bundle. Resumability (Qwik) avoids replaying work on the client.
Interview questions
- Difference between CSR and SSR?
- What is hydration and why can it be slow?
- When would you pick SSG over SSR?
- What is the islands architecture?