WEB PERFORMANCE CODING
Web performance problems
70 problems for the web performance coding round: compute metrics from raw numbers, observe real users, load and cache resources, and keep the main thread free, then run tests against it. 27 easy, 34 medium, and 9 hard.
The tests play the browser's part on this page: a clock you control, frames, observers, the network, and Cache Storage, each working the way its spec says. Your code is saved as you go, and hints are free. Sign in with Google to see the solutions.
70 of 70 problems
Metrics math
- Rate a metricRate an LCP, INP, CLS, FCP, or TTFB value as good, needs improvement, or poor, with the thresholds web-vitals uses.
- CLS with session windowsGroup layout shifts into session windows the way web-vitals does, and report the largest window as the page's CLS.
- The 75th percentile of field dataSummarize real visits' samples of a metric the way Core Web Vitals are judged: the 75th percentile, the share that's good, and whether it passes.
- INP from Event Timing entriesGroup event entries into interactions and pick INP the way web-vitals does: the longest, skipping one for every 50 interactions.
- The final LCPFind the LCP web-vitals reports from a page's timeline: the last candidate before it stops, after a key press, a click, or the page being hidden.
- Break down TTFBCompute TTFB and its five parts from a navigation entry the way web-vitals' attribution build does, prerendered pages included.
- Break down LCPSplit an LCP into time to first byte, resource load delay, load duration, and render delay, with web-vitals' matching and clamping rules.
- Total Blocking TimeAdd up the blocking part of each long task between FCP and TTI, clipping tasks at both ends the way Lighthouse does.
- Score a metric like LighthouseTurn a metric's value into Lighthouse's score on a log-normal curve set by its p10 and median, with the clamps, the boost, and the rounding.
- Lighthouse's Performance scoreCombine five metric scores into the Performance score with Lighthouse's weights, and round it the way the report's gauge shows it.
Observing real users
- Observe LCPWatch LCP candidates with a buffered PerformanceObserver and report the last one once: after a key press, a click, or the page being hidden.
- Observe CLSTrack layout shifts in live session windows and report CLS when the page is hidden, and again on a later hide only if it changed.
- Observe INPFeed event and first-input entries into the 10 longest interactions, pick INP the way web-vitals does, and report it when the page is hidden.
- Send metrics when the page is hiddenQueue metrics and send them in one request when the page is hidden: sendBeacon first, and fetch with keepalive when it's missing or refuses.
- Time a function with User TimingWrap a function in marks and a measure, for sync and async work, errors and overlapping calls included, and clear the marks afterwards.
- Summarize User Timing measuresTurn the page's measure entries into one row per name, with its count, min, max, mean, and 75th percentile, slowest first.
- Report the worst long animation framesKeep the long animation frames that blocked input longest, break each into work and render time, and add up script time by source file.
- Metrics after a back/forward cache restoreReport FCP with its navigation type, then start it over at each back/forward cache restore, timed to the second frame, as web-vitals does.
- Summarize Resource TimingAdd up what the page fetched by initiatorType, and pick out the cache hits and the cross-origin files whose details the browser hides.
- Parse a Server-Timing headerParse a Server-Timing header into names, durations, and descriptions the way the W3C spec does: quoted strings, missing values, and repeats.
Loading resources
- Lazy-load imagesLoad each photo only as it nears the screen, with one IntersectionObserver and a margin, and all at once where it isn't there.
- Prefetch on hoverPrefetch a link's page once the pointer has rested on it for 65 ms, once per URL, and never on Save-Data or a 2G connection.
- Pick a srcset candidateParse a srcset the way the HTML Standard does, give each candidate a density from the slot width, and pick the image a browser requests.
- Evaluate a sizes attributeWork out an image's slot width from its sizes attribute and the viewport: media conditions, px, vw, and em, invalid entries, and the 100vw fallback.
- Choose origins to preconnectFrom the URLs a page requests, list the other origins worth a preconnect: once each, by first use, a few at most, with crossorigin where it's needed.
- Load a script onceLoad a script on demand with one
<script async>per URL, share its promise between callers, and let a later call retry after a failure. - A fetch queue with prioritiesRun at most
limitfetches at a time, starting high-priority requests before low ones and each priority first come, first served. - The longest critical request chainFollow each request back to the document through its initiators, and find the chain that ends last, as Lighthouse's Network dependency tree reports it.
- Find render-blocking resourcesPick out the head elements that hold up the first render, by the HTML Standard's rules for stylesheets, scripts, and blocking="render".
- Negotiate an image formatPick AVIF, WebP, or JPEG from a request's Accept header the way RFC 9110 reads it: q-values, wildcards, the most specific range, and ties.
Caching
- Parse Cache-ControlTurn a Cache-Control header into its directives, with numbers for seconds, quoted values, and the RFC 9111 rules for duplicates and bad values.
- HTTP freshnessDecide whether a stored response is fresh, usable while it revalidates, or stale, from its headers and timings, as RFC 9111 and RFC 5861 compute it.
- Revalidation headersMake a request conditional with If-None-Match and If-Modified-Since from a stored response, then freshen it with the headers of a 304.
- Compare ETagsStrong and weak entity tag comparison, and an If-None-Match header evaluated the way RFC 9110 says a server does.
- Cache firstA service worker fetch handler that answers the shop's own GET requests from Cache Storage first, and stores what the network sends.
- Network first, with a timeoutAnswer from the network, fall back to the cache after a timeout or a network error, and keep the cache up to date when the network answers late.
- Stale-while-revalidate in a service workerAnswer from the cache at once and refresh it in the background with waitUntil, falling back to the network when nothing is cached.
- Precache and clean upInstall a versioned list of files all or nothing, and delete the caches an older service worker left behind when the new one activates.
- A cache with a byte budgetAn in-memory cache that evicts least recently used entries to keep its bodies under a byte budget, and refuses a body too big to ever fit.
- Match a request with VaryPick the stored response a request may reuse by comparing the request headers each response's Vary names, as RFC 9111 says, and choose among several.
The main thread
- Yield to the main threadWrite
yieldToMain():scheduler.yield()where the browser has it, and a promise a 0 mssetTimeoutresolves where it doesn't. - Process in chunksWork through a long list without long tasks: yield to the browser once 50 ms have passed since the last break.
- An idle task queueRun queued background tasks in idle callbacks while time remains, carry on in the next idle period, and keep going on a page that's never idle.
- Run work after the next paintReturn a promise that resolves right after the browser paints the next frame: a frame callback, then a task queued from inside it.
- A search box that answers at onceShow what the shopper typed right away, and run the costly filter after the next paint, for the latest input only.
- Batch layout reads and writesQueue layout reads with
measureand style writes withmutate, and run every read, then every write, in one animation frame. - Promise calls to a workerCall functions in a web worker as promises over
postMessage: match each answer to its call by id, and reject with the worker's error message. - Render a long list in time slicesRender thousands of rows a frame at a time within a time budget, and let a newer render cancel the old one.
- A task scheduler with prioritiesRun user-blocking, user-visible, and background tasks in priority order, yield once 50 ms have passed, and drop tasks whose signal aborts.
- Break down an interactionSplit an INP interaction into input delay, processing duration, and presentation delay, from its event entry and the others in its frame, as web-vitals does.
Rendering and stability
- Visible rows in a virtual listWork out which rows a fixed-height virtual list renders for a scroll position: the rows in view, overscan on each side, clamped to the list.
- Virtual list with measured heightsKeep a virtual list's row offsets as rows are measured: prefix sums you can update, a binary search for the first row in view, and estimates for the rest.
- Fix layout thrashingRewrite a function that sizes cards one at a time, reading layout right after each style write, so every read comes before any write.
- Layout shift scoreScore one element's layout shift the way the Layout Instability spec does: the impact fraction times the distance fraction, clipped to the viewport.
- Layout shift with many elementsScore a frame in which many elements moved: the exact area of the union of their visible boxes, and the largest move of any of them.
- Frame rate reportTurn requestAnimationFrame timestamps into a report: frames per second, the frames dropped in long gaps, and the longest frame.
- Throttle to animation framesWrap a function so it runs at most once per animation frame, with the latest call's arguments, and can be cancelled.
- Infinite scroll with a sentinelLoad the next page of reviews when a sentinel nears the screen, with IntersectionObserver: one load at a time, and no more once the last page is in.
- Reserve space for imagesGive photos, videos, and embeds their size before they load, from data attributes, so the text under them doesn't jump when they arrive.
- Animate with transformSlide an element with
transform: translateX()in animation frames, from each frame's timestamp and an easing, ending exactly at the target.
Budgets and analysis
- Check a build against its budgetCompare a page's requests with a budget.json budget: transfer sizes in KiB and request counts per resource type, the total and third parties included.
- Diff two builds' bundle sizesCompare two builds' chunks: what was added or removed, what changed and by how much, the biggest change first, and the total.
- Find duplicate packages in a bundleFrom a bundle's module paths and the installed versions, find the packages bundled in more than one version and what each copy weighs.
- Pick the median Lighthouse runFrom several Lighthouse results, keep the run closest to the median FCP and TTI, as Lighthouse's computeMedianRun picks it.
- Catch a p75 regressionCompare a candidate's samples with a baseline's at the 75th percentile, and flag a regression only with enough samples and past a threshold.
- Summarize a HAR fileCount a HAR's requests and bytes by type, with Chrome's transfer size when it's there and the HAR 1.2 sizes when it isn't, and list the largest files.
- Self time from a trace, like Bottom-upTurn one thread's nested trace events into DevTools' Bottom-up table: self time and total time per name, in ms, with recursion counted once.
- Read a CrUX histogramFrom a CrUX API histogram, report the good, needs improvement, and poor shares and which bin holds the 75th percentile.
- Speed Index from a filmstripCompute Speed Index from filmstrip frames' visual progress: the area above the progress curve, added up the way WebPageTest does it.
- The cost of each third partyGroup a page's requests and main-thread tasks by third party, merging each company's origins, and rank them by main-thread time.