Browser & Web Performance Middle cheat sheet: interview answers
Every question of this level with its correct answer and explanation, on one page for a quick review before the interview.
1. What problem does this code cause?
for (const card of cards) { const h = card.offsetHeight; card.style.height = h + 10 + "px"; }Correct answer: Layout thrashing: reads force a synchronous layout
Reading geometry after changing styles forces the browser to recalculate layout immediately. Batch all reads first, then all writes.
2. Which CSS properties can usually be animated without triggering layout or paint?
Correct answer:
transformandopacityThey can be handled by the compositor on an already painted layer, so animations stay smooth even if the main thread is busy.
3. What is the risk of adding
will-change: transformto many elements?Correct answer: Each may get its own layer, costing GPU memory
will-changeis a hint for elements that are about to animate, not a general speed-up. Overuse leads to layer explosion.4. Why is
requestAnimationFramebetter thansetInterval(fn, 16)for visual updates?Correct answer: It runs right before the browser renders a frame
Timers drift and aren't aligned with frames, so updates can be dropped or done twice. rAF also adapts to 120 Hz displays.
5. What does
content-visibility: autodo?Correct answer: Skips rendering work for offscreen content
On long pages it can greatly cut initial rendering time. Pair it with
contain-intrinsic-sizeso the scrollbar doesn't jump.6. Why does a very large DOM (tens of thousands of nodes) hurt responsiveness?
Correct answer: Style recalculation and layout get more expensive
Rendering cost grows with the number of nodes affected. Virtualizing long lists keeps only visible rows in the DOM.
7. What does CSS
contain: layout painttell the browser?Correct answer: Inner changes don't affect layout or paint outside
Containment lets the browser skip recalculating the rest of the page when a widget changes internally.
8. Which change usually causes only a repaint, without layout?
Correct answer: Changing
background-colorColor doesn't change geometry, so layout is skipped, but pixels must be repainted. Geometry and DOM changes trigger layout.
9. What is the main thread responsible for in a typical browser tab?
Correct answer: JavaScript, style calculation, layout and painting
Networking and compositing run on other threads, but JS and most rendering share the main thread, so they compete.
10. Which three parts make up the latency of a single interaction in INP?
Correct answer: Input delay, processing time and presentation delay
Input delay is waiting for the main thread, processing is running handlers, presentation is rendering the next frame.
11. A click handler does heavy, non-urgent work after updating the UI. How can you make the update appear sooner?
button.addEventListener("click", async () => { showSpinner(); // ...heavy work here });Correct answer: Yield with
await scheduler.yield(), then do the workYielding lets the browser paint the spinner before continuing. Without it, the frame waits for the whole handler.
12. What is the advantage of
scheduler.yield()oversetTimeout(resolve, 0)for yielding?Correct answer: The continuation goes to the front of the queue
Both let the browser handle input and render, but with
setTimeoutyour remaining work waits behind any other tasks.13. When are Web Workers a good fit for improving INP?
Correct answer: For CPU-heavy work that doesn't touch the DOM
Workers run on another thread and communicate via messages. They can't access the DOM directly.
14. What does Total Blocking Time (TBT) measure in a lab test?
Correct answer: The sum of long-task time beyond 50 ms each
A 120 ms task contributes 70 ms. TBT correlates with INP and is useful because labs can't measure real interactions.
15. Which INP value is reported for a page with many interactions?
Correct answer: Roughly the worst interaction, minus rare outliers
This approximates the 98th percentile within a visit so a single random hiccup doesn't dominate long sessions.
16. A search box filters a 5 000-item list on every keystroke and typing feels laggy. Which fix helps INP the most?
Correct answer: Update the input at once and defer the filtering
The keystroke's frame should only show the typed character. The heavy list update can happen later or in smaller chunks.
17. What does presentation delay in INP mostly depend on?
Correct answer: How much rendering work the next frame needs
Even fast handlers can produce slow interactions if they change a huge part of the DOM.
18. What does
requestIdleCallbackdo?Correct answer: Runs a callback when the browser is idle
It's good for things like sending analytics or prefetching. Don't use it for work the user is waiting to see.
19. Why can third-party scripts hurt INP even if they load with
async?Correct answer: They still execute on your main thread once loaded
asynconly avoids blocking the parser. Audit third parties, load them later, or replace heavy embeds with facades.20. LCP can be split into four parts. Which list is correct?
Correct answer: TTFB, load delay, load duration, render delay
Breaking LCP down shows where time goes: slow server, late discovery of the image, a big file, or rendering blocked by JS/CSS.
21. The LCP image is set as a CSS
background-image. Why does that often hurt LCP?Correct answer: The preload scanner can't see it in the HTML
Use an
<img>in the HTML or add<link rel="preload" as="image">so the browser discovers it early.22. What does
fetchpriority="high"on the LCP<img>do?Correct answer: Asks to fetch this image ahead of similar resources
Images often start with low priority until layout shows they're in the viewport. The hint skips that wait for the hero image.
23. Why can a client-side rendered SPA have a poor LCP even on a fast network?
Correct answer: The element doesn't exist until JS and data are in
Server-side rendering or static generation puts the main content in the initial HTML so it can render without waiting for JS.
24. What does a
103 Early Hintsresponse let the server do?Correct answer: Send
Linkheaders before the final responseWhile the server is still generating the page, the browser can already fetch critical CSS or connect to other origins.
25. What does an image CDN typically do?
Correct answer: Resizes and converts images on the fly
You keep one original, and each device gets a suitably sized AVIF or WebP from a server close to it.
26. LCP is measured until when?
Correct answer: Until the user first interacts or leaves
After an interaction, new large elements are often a result of the user's action, so the browser stops reporting candidates.
27. Which layout shifts are excluded from CLS?
Correct answer: Shifts within 500 ms after a user input
Expected shifts, such as opening an accordion after a click, shouldn't be penalized. Scrolling doesn't count as such input.
28. How is the CLS value for a page visit computed?
Correct answer: The largest session window of grouped shifts
Session windows keep CLS fair for long-lived pages like SPAs that would otherwise accumulate an ever-growing score.
29. How can you reduce CLS caused by web fonts?
Correct answer: Match fallback metrics with
size-adjustIf the fallback takes the same space as the web font, swapping doesn't move text.
optionalavoids late swaps entirely.30. A banner is inserted at the top of the page after an API call and pushes content down. What is the best fix?
Correct answer: Reserve space in advance or show it as an overlay
Content arriving late is fine as long as it doesn't move what the user is already looking at.
31. Why are animations with
transformbetter than animatingtopfor CLS?Correct answer: They don't change layout at all
Animating
top,marginorheightmoves layout boxes, which can be reported as layout shifts and costs layout work each frame.32. Why must a preloaded font have the
crossoriginattribute?<link rel="preload" href="/fonts/inter.woff2" as="font" type="font/woff2" crossorigin>Correct answer: Fonts use CORS mode, or they download twice
This is needed even for same-origin fonts. A mismatch shows up as an 'unused preload' warning in the console.
33. What does
<link rel="modulepreload">do differently frompreload?Correct answer: It fetches, parses and compiles an ES module
It avoids the waterfall where each
importis discovered only after the previous module is downloaded.34. What does code splitting with dynamic
import()give you?Correct answer: Feature code loads only when it's needed
Splitting by route or by rarely used widgets (dialogs, editors, charts) reduces JS that must be parsed and executed at startup.
35. What does tree shaking rely on to remove unused code?
Correct answer: Static ES module
import/exportsyntaxCommonJS
requireis dynamic, so bundlers often can't prove code is unused. Side effects in modules also block removal.36. What is a facade for a heavy third-party embed, like a video player?
Correct answer: A light static preview that loads the embed on demand
Many visitors never press play, so they never pay for the player's hundreds of kilobytes of JS.
37. What does the Speculation Rules API allow?
<script type="speculationrules"> { "prerender": [{ "where": { "href_matches": "/product/*" }, "eagerness": "moderate" }] } </script>Correct answer: Declaratively prefetching or prerendering next pages
Prerendering loads and renders the page in the background.
eagernesscontrols when, e.g. on hover formoderate.38. Why should you avoid preloading too many resources?
Correct answer: They compete for bandwidth with critical resources
Preload raises priority. When everything is high priority, nothing is, and the LCP resource may arrive later.
39. What does
Cache-Control: max-age=60, stale-while-revalidate=600allow?Correct answer: Fresh for 60 s, then stale served while revalidating
Users get an instant response and the cache updates for the next request. It's a trade-off between freshness and speed.
40. What is
s-maxageused for?Correct answer: Setting freshness for shared caches like CDNs
A common setup: short or no browser caching, longer CDN caching, with purges on deploy.
41. What is the
Varyresponse header for?Correct answer: It lists the request headers that affect the response
For example
Vary: Accept-Encodingkeeps Brotli and gzip variants apart. Varying on very diverse headers likeUser-Agenthurts cache hit rates.42. A response has no
Cache-ControlorExpires, but hasLast-Modified. Can the browser cache it?Correct answer: Yes, it may use heuristic freshness
Heuristic caching surprises people after deploys. Always set explicit caching headers.
43. What does
must-revalidateadd to a cached response?Correct answer: Once stale, it can't be used without revalidation
Without it, caches may serve stale content in some cases (e.g. when disconnected). It doesn't affect fresh responses.
44. Which service worker caching strategy fits hashed static assets best?
Correct answer: Cache first, falling back to network
Hashed files never change at the same URL, so serving them from cache is always correct and fastest.
45. Which strategy fits an API response that should be fresh but must also work offline?
Correct answer: Network first, with a cached fallback
Users get current data online and the last known data offline. Stale-while-revalidate is the option when speed matters more than freshness.
46. What is the Cache Storage API (
caches.open) compared to the HTTP cache?Correct answer: A storage you control from JavaScript
Entries stay until your code deletes them or the browser evicts the origin's storage, so versioning and cleanup are your job.
47. Which cross-origin request is sent without a preflight?
Correct answer:
POSTwithapplication/x-www-form-urlencodedSimple requests use GET, HEAD or POST with safelisted headers and one of three content types (form-urlencoded, multipart, text/plain).
48. The frontend sends
fetch(url, { credentials: "include" })to another origin. What must the response contain?Correct answer: The exact origin, plus
Allow-Credentials: trueWith credentials the wildcard is not allowed. Also, cookies must be
SameSite=None; Secureto be sent cross-site.49. Your JS can't read a custom
X-Total-Countheader from a cross-origin response. Why?Correct answer: It must be listed in
Access-Control-Expose-HeadersHeaders like
Content-Typeare readable by default. Pagination or rate-limit headers need explicit exposure.50. What does
Access-Control-Max-Agedo?Correct answer: Lets the browser cache the preflight result
Browsers cap the value (for example, Chrome uses at most 2 hours), but even short caching removes many round trips.
51. A server reflects the request's
OriginintoAccess-Control-Allow-Originfor an allowlist of sites. Which header should it also send?Correct answer:
Vary: OriginOtherwise a CDN could cache the response with one origin's header and serve it to another origin, breaking CORS.
52. Does a CORS error mean the request never reached the server?
Correct answer: No: the browser may only hide the response from JS
That's why CORS isn't a CSRF defense: a cross-site form POST can still change state on the server.
53. What is an opaque response?
Correct answer: A
no-corsfetch result with nothing readableService workers can cache opaque responses, but can't check if they succeeded, and they may take a lot of storage quota.
54. What is CSRF?
Correct answer: Another site triggers a request with the user's cookies
Defenses:
SameSitecookies, anti-CSRF tokens, checkingOrigin/Sec-Fetch-Site, and never changing state on GET.55. What is clickjacking and which header defends against it?
Correct answer: A hidden iframe tricks clicks; use
frame-ancestorsframe-ancestors 'none'or'self'is the modern option;X-Frame-Options: DENYis the older equivalent.56. What does
X-Content-Type-Options: nosniffdo?Correct answer: Stops the browser from guessing the MIME type
MIME sniffing could turn an uploaded file into executable script or style. With
nosniffthe declaredContent-Typeis respected.57. What does the
integrityattribute (Subresource Integrity) protect against?<script src="https://cdn.example.com/lib.js" integrity="sha384-..." crossorigin="anonymous"></script>Correct answer: A compromised CDN serving a modified file
The hash pins the exact file contents. It's mainly useful for versioned third-party files that never change.
58. Why is
<a href={userUrl}>dangerous ifuserUrlisn't validated?Correct answer:
javascript:alert(1)runs script on clickEscaping text doesn't help with URLs. Allow only
http:andhttps:(and maybemailto:) schemes.59. What must a
messageevent handler check before trustingevent.data?window.addEventListener("message", (event) => { // ... });Correct answer: That
event.originis an expected originAny window can post messages to yours. When sending, set the exact
targetOrigininstead of*too.60. Why does CSP with
'unsafe-inline'inscript-srcprovide little XSS protection?Correct answer: Injected inline scripts are allowed to run
Most XSS payloads are inline. Use nonces or hashes so only scripts you put on the page can run.
61. How does a nonce-based CSP decide which inline scripts may run?
Content-Security-Policy: script-src 'nonce-r4nd0m' <script nonce="r4nd0m">init()</script>Correct answer: Only scripts with this response's random nonce run
An attacker can't guess a fresh random nonce. Reusing the same nonce across responses defeats the protection.
62. What does
Referrer-Policy: strict-origin-when-cross-origin(the browser default) send?Correct answer: The full URL only to the same origin
Full URLs can leak tokens or private paths to third parties; the default limits that.
63. What is the difference between same-site and same-origin?
Correct answer: Same-origin also requires the same host and port
https://app.example.comandhttps://api.example.comare same-site but cross-origin. SameSite cookies use the site concept.64. What is the back/forward cache (bfcache)?
Correct answer: A full in-memory snapshot of the page
Restored pages keep their JS state. An
unloadlistener is a common reason pages can't use bfcache.65. How can a page detect that it was restored from bfcache?
Correct answer: In
pageshow,event.persistedistrueUse it to refresh stale data (e.g. cart contents). Use
pagehideinstead ofunloadfor cleanup.66. What is the most reliable moment to send analytics before the user leaves?
Correct answer: On
visibilitychangetohidden, withsendBeaconOn mobile,
unloadoften doesn't fire when the app is switched or killed.hiddenis the last reliable signal.67. How can you mark custom points in time to see them in DevTools and measure them in code?
Correct answer:
performance.mark()andperformance.measure()Marks and measures show up in the Performance panel and can be collected with a
PerformanceObserver.68. How do you collect LCP, INP and CLS from real users with little code?
Correct answer: Use the
web-vitalslibrary and report its valuesThe library wraps
PerformanceObserverand handles edge cases like bfcache restores and background tabs.69. What is CrUX (Chrome UX Report)?
Correct answer: A public dataset of real-user Chrome metrics
It's the field data shown in PageSpeed Insights and Search Console, aggregated over a rolling 28-day window.
70. What is the
Server-Timingheader useful for?Correct answer: Reporting backend timings to DevTools
It helps explain a slow TTFB without opening server logs. Avoid exposing sensitive details to everyone.
71. Why does Resource Timing show zeros for DNS, connect and request phases of some cross-origin resources?
Correct answer: They're hidden without
Timing-Allow-OriginTiming details could leak information across origins, so they're opt-in. Your own CDN should send the header.
72. What problem of HTTP/2 over TCP does HTTP/3 solve?
Correct answer: TCP head-of-line blocking across streams
HTTP/3 runs over QUIC (on UDP) with built-in TLS 1.3, which also makes connection setup faster. It helps most on lossy mobile networks.
73. What does the
Clear-Site-Dataheader do, for example on logout?Clear-Site-Data: "cache", "cookies", "storage"Correct answer: Deletes the site's cache, cookies and storage
It makes logout on shared computers more thorough, removing data the client could otherwise keep.
74. What does
Permissions-Policy: camera=(), geolocation=(self)do?Correct answer: No camera at all; geolocation only for the same origin
It limits which powerful features the page and embedded third parties can even request, reducing the attack surface.
75. Why does a third-party cookie set inside an embedded iframe often not work anymore?
Correct answer: Browsers block or partition third-party cookies
Safari and Firefox block cross-site tracking cookies by default. CHIPS (
Partitioned) gives embeds a separate cookie jar per top-level site.