📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

You're a backend engineer and someone asks: what actually happens in the browser after your ASP.NET Core server sends back an HTML page? Explain how the browser turns HTML, CSS and JavaScript into pixels: parsing, the DOM and CSSOM, layout and paint, and how the JavaScript event loop decides when your code runs.

How a browser parses HTML into the DOM, CSS into the CSSOM, runs layout, paint and compositing, how scripts block parsing, and how the single-threaded event loop with tasks and microtasks schedules JavaScript.

Beginner Theory Beginner browser-rendering critical-rendering-path dom event-loop frontend javascript

🎯 Key points

  • HTML is parsed incrementally into the DOM tree; CSS into the CSSOM
  • DOM + CSSOM = render tree, then layout (geometry), paint, composite
  • Classic <script> blocks the HTML parser; defer and type=module do not
  • CSS is render-blocking: nothing paints until the CSSOM for the page is ready
  • JavaScript runs on one main thread: one task at a time, then all microtasks, then maybe a render
  • Promise callbacks/await continuations are microtasks; setTimeout and events are tasks
  • Long tasks (>50 ms) delay input handling: INP (which replaced FID as a Core Web Vital in March 2024) should stay under 200 ms
  • Server choices (HTML size, compression, caching, script placement) shape LCP and INP, most on slower mobile networks

⏱ 30-second answer

The browser streams and parses the HTML into the DOM and parses CSS into the CSSOM. Together they form the render tree, which goes through layout (sizes and positions), paint (pixels per layer) and compositing (layers combined on the GPU). A plain <script> blocks the parser until it downloads and runs, which is why we use defer or type="module"; CSS is render-blocking. All page JavaScript runs on one main thread driven by the event loop: take one task (a click, a timer, a network callback), run it to completion, drain the microtask queue (promise continuations, await), then render if a frame is due. The trade-off to remember: anything that hogs the main thread, whether your script or a huge DOM the server sent, freezes both input and rendering.

🗣 Full answer (senior)

How I would answer this in an interview

"When my ASP.NET Core endpoint returns HTML, the browser doesn't wait for the whole response. It parses the bytes as they stream in, tokenises the markup and builds the DOM, a tree of nodes that JavaScript can query and change. Whenever it meets a stylesheet it fetches and parses it into the CSSOM. The browser won't paint until it has the CSS, because painting unstyled content and then restyling would flash, so CSS is render-blocking. It then combines DOM and CSSOM into a render tree of visible elements, runs layout to work out every box's geometry, paints each layer into pixels and composites the layers, usually on the GPU.

Scripts are the interesting part. A plain <script src> stops the parser: the browser has to download and execute it, because the script might call document.write or read the DOM so far. That's why modern pages use defer or type=\"module\", which download in parallel and run after parsing finishes, in order. All of that JavaScript runs on a single main thread managed by the event loop: pick one task from a queue, such as a click handler, a timer or a fetch response, run it to completion, then run every microtask, which is where promise callbacks and code after await live, and then let the browser render a frame if one is due, roughly every 16 ms at 60 Hz.

The mistake I see backend engineers make is assuming the browser is like a multi-threaded server. It isn't: one 300 ms loop over a big JSON payload blocks clicks, scrolling and painting for 300 ms. So the things I control on the server, like HTML size, how many DOM nodes I render, caching and compression headers, and whether scripts are deferred, directly decide how fast the page feels."


The pipeline at a glance

Stage Input Output What blocks it
Parse HTML Byte stream DOM Synchronous <script>
Parse CSS Stylesheets CSSOM Slow CSS download
Style DOM + CSSOM Computed styles / render tree Large, complex selectors
Layout Render tree Box geometry Forced synchronous layout from JS
Paint Geometry + styles Layer bitmaps Expensive effects (shadows, filters)
Composite Layers Frame on screen Too many layers

Script loading options

Attribute Downloads Runs Order kept Use for
none Blocks parser Immediately Yes Almost never now
async In parallel As soon as downloaded No Independent scripts (analytics)
defer In parallel After parsing, before DOMContentLoaded Yes App scripts
type="module" In parallel Deferred by default Yes Modern bundles (Vite output)

Tasks vs microtasks

Queue Examples When it runs
Task (macrotask) Event handlers, setTimeout, MessageChannel, network callbacks One per loop turn
Microtask Promise .then, code after await, queueMicrotask All of them, right after the current task
Render steps requestAnimationFrame, style, layout, paint When a frame is due, between tasks

Production example

An internal dashboard rendered a 12,000-row table server-side and loaded a 900 KB script without defer. First paint took 4.1 s on office laptops. Paginating to 100 rows, adding defer and enabling Brotli brought first paint to 0.9 s and the longest main-thread task from 1.2 s to 80 ms.

🔍 What the interviewer is checking

Checks that a backend engineer has a correct mental model of how the browser processes what the server sends, especially single-threaded JavaScript.

Green flags

  • Describes DOM, CSSOM, layout, paint and compositing in order
  • Knows why plain scripts block parsing and what defer/module change
  • Explains tasks vs microtasks and where await continuations run
  • Connects server choices (size, headers, DOM size) to rendering cost

Red flags

  • Thinks the browser waits for the whole page before doing anything
  • Believes JS in the page is multi-threaded
  • Can't explain why a long loop freezes the UI

📚 Learn in depth

1. Bytes to tokens to nodes

The HTML parser is a state machine defined by the WHATWG HTML spec. It is deliberately forgiving: unclosed tags and bad nesting are repaired by rules, not rejected. It works incrementally, so a server that flushes the <head> early (for example via streaming rendering) lets the browser start fetching CSS before the body arrives.

response bytes -> decoder (charset) -> tokenizer -> tree builder -> DOM
                                                 |
                           <link rel=stylesheet> +-> fetch CSS -> CSSOM
                           <script>              +-> fetch + execute (blocks tree builder)

A preload scanner runs ahead of the main parser while it is blocked on a script and starts downloading images, CSS and scripts it can see. That's why a blocking script is bad but not catastrophic.

2. Why CSS blocks rendering and sometimes scripts

A script might read getComputedStyle, so the browser won't run a script until earlier stylesheets are parsed. A slow CSS file therefore delays both painting and script execution.

3. Layout, paint, composite

DOM + CSSOM
    |
    v
render tree (display:none elements excluded)
    |
    v
layout  -> x, y, width, height for every box
    |
    v
paint   -> draw commands per layer
    |
    v
composite -> GPU combines layers -> frame

Changing transform or opacity usually only needs compositing (cheap). Changing width or inserting nodes needs layout again (expensive). Reading offsetHeight right after a write forces a synchronous layout ("layout thrashing").

4. The event loop

The browser's main thread loops roughly like this:

while (true) {
  task = pickOldestTask()        // click, timer, fetch callback, message
  run(task)                      // to completion: no pre-emption
  drainMicrotasks()              // promise reactions, await continuations
  if (frameDue) {
    runAnimationFrameCallbacks() // requestAnimationFrame
    style(); layout(); paint()
  }
}

Compared with .NET: there is no thread pool for your page code. await in JavaScript is closer to await in a UI app with a SynchronizationContext: the continuation always comes back to the single main thread. Web Workers are the only way to run JS in parallel, and they cannot touch the DOM.

5. What the server controls

Server decision Effect in the browser
Response compression (Brotli/gzip) Fewer bytes before parsing completes
Cache-Control on static assets Repeat visits skip downloads
HTML size and DOM node count Parse, style and layout time
Script tags with defer/module Parser never blocked
Link: rel=preload or early hints (103) Critical assets fetched sooner

Try it yourself

  1. Open Chrome DevTools → Performance, record a reload of any page and find the Parse HTML, Layout and Paint entries in the flame chart.
  2. Paste setTimeout(() => console.log('task')); Promise.resolve().then(() => console.log('microtask')); console.log('sync'); into the console and explain the order.
  3. Serve a page from a Minimal API with a blocking <script> that sleeps 2 s, then add defer and compare first paint in the Performance panel.
  4. Run a 500 ms busy loop in a click handler and watch the Long Task flag and the frozen spinner.
  5. Run Lighthouse on a page and find the "Eliminate render-blocking resources" audit.

💻 Code

A Minimal API serving a page, and the browser-side code showing task vs microtask order and a non-blocking script. ```csharp // Program.cs (.NET 10) var builder = WebApplication.CreateBuilder(args); builder.Services.AddResponseCompression(o => o.EnableForHttps = true); // fewer bytes to parse var app = builder.Build(); app.UseResponseCompression(); app.UseStaticFiles(); // serves wwwroot/app.js with caching headers set below if configured app.MapGet("/", () => Results.Content("""

Orders

    """, "text/html")); app.Run(); ``` ```javascript // wwwroot/app.js - runs after the DOM is parsed (module = deferred) console.log('1: sync'); setTimeout(() => console.log('4: task (timer)'), 0); Promise.resolve().then(() => console.log('3: microtask')); queueMicrotask(() => console.log('3b: microtask')); console.log('2: sync'); // Build DOM in one go: one layout instead of one per item const items = ['A-1001', 'A-1002', 'A-1003']; const fragment = document.createDocumentFragment(); for (const id of items) { const li = document.createElement('li'); li.textContent = id; // textContent, not innerHTML: no HTML parsing, no XSS fragment.append(li); } document.getElementById('orders').append(fragment); ```

    ⚠ Common mistakes

    • Mistake: Thinking JavaScript in the page runs on multiple threads like ASP.NET Core requests. Why it is wrong: Page JS runs on one main thread; a long loop blocks input and painting and shows up as a poor INP (Interaction to Next Paint). Instead: Keep tasks under 50 ms, chunk work or move it to a Web Worker.
    • Mistake: Putting <script src> in the <head> without defer. Why it is wrong: It stops the parser until the script downloads and runs. Instead: Use defer or type="module".
    • Mistake: Believing setTimeout(fn, 0) runs before a resolved promise callback. Why it is wrong: Promise reactions are microtasks and run before the next task. Instead: Learn the task/microtask order.
    • Mistake: Sending huge server-rendered tables or deeply nested markup. Why it is wrong: Style and layout cost grows with node count, and mobile CPUs are several times slower than a developer laptop. Instead: Paginate or virtualise; keep the DOM lean.
    • Mistake: Reading layout properties (offsetHeight, getBoundingClientRect) inside a loop that also writes styles. Why it is wrong: Each read after a write forces the browser to recalculate style and layout synchronously, again and again: this is layout thrashing, and it can turn a 2 ms loop into 200 ms. Instead: Batch all reads first, then all writes (or write inside requestAnimationFrame).
    • Mistake: Treating the DOM as the HTML source text. Why it is wrong: The DOM is a live object tree after error correction and script changes. Instead: Inspect the Elements panel, not View Source, to see what the browser built.
    • Mistake: Still quoting FID as the responsiveness metric. Why it is wrong: Google replaced First Input Delay with INP in March 2024; INP measures every interaction, not just the first. Instead: Target INP ≤ 200 ms at the 75th percentile of real users.

    🏛 Senior insight: trade-offs

    A backend engineer doesn't need to master rendering internals, but they own several of its inputs: bytes on the wire, cacheability, HTML shape and how quickly the first byte arrives. Most "the frontend is slow" investigations I've seen end at something the server could fix: an uncompressed 2 MB JSON blob, no-store on hashed assets, or a page that renders thousands of nodes nobody scrolls to.

    Option When it fits Cost When not to
    Server-rendered HTML (Razor, Blazor static SSR) Content pages, forms, fast first paint Server CPU per request Highly interactive canvases
    SPA (React/Angular) with JSON API Rich interaction after load Bigger JS bundle, slower first load Mostly static content
    Streaming/early flush Slow data, want fast <head> More complex error handling Responses that must fail atomically

    Measure with the Performance panel and Lighthouse locally, and with real-user monitoring (Application Insights browser SDK or Core Web Vitals in the field) in production; lab numbers on a fast laptop hide what mobile users in regional Australia see.

    🔗 Follow-ups the interviewer may ask

    1. When: Candidate mentions the server's response streaming into the parser Why: Checks they know what the HTTP response the browser parses actually contains
      How to answer

      An HTTP message has three parts: a start line, headers and an optional body. A request's start line is the method, target and version (GET /orders/42?include=lines HTTP/1.1); a response's is the status line (HTTP/1.1 200 OK). Headers carry metadata such as Content-Type, Accept and Authorization; a blank line separates them from the body.

      In an API, the route identifies the resource, the query string filters or shapes it, headers carry cross-cutting metadata, and the body carries the representation being created or changed. ASP.NET Core exposes all of this through HttpContext.Request and HttpContext.Response, and model binding maps it onto parameters. The trade-off: URLs are logged and cached everywhere, so anything sensitive goes in headers or the body, never the query string.

    2. When: Candidate mentions long tasks blocking the UI Why: Checks they know the browser's only real parallelism model and its limits
      How to answer

      A Web Worker runs a script on a separate thread with its own event loop. It can't touch the DOM; it talks to the page with postMessage (structured clone or transferable objects). Use it for CPU-heavy work such as parsing a large file, image processing or crypto, so the main thread stays responsive. The cost is copying data across and more complex code, so first check whether the work could be done on the server or paginated.

    3. When: Candidate mentions defer or scripts running after parsing Why: Checks they understand page lifecycle events
      How to answer

      DOMContentLoaded fires when the HTML is fully parsed and deferred and module scripts have run, without waiting for images, iframes or late stylesheets. load fires only when every subresource, including images, has finished. Most app code only needs the DOM, so it should run at DOMContentLoaded (or simply as a defer/type="module" script): users can interact sooner, which helps perceived performance and INP. Waiting for load holds interactivity hostage to the slowest image. Use load only for code that genuinely needs final image sizes or every resource, such as measuring layout.

    More in Web Basics

    Last updated 23 Nov 2026.

    🌐 Sangam's Webring

    ⏪ Previous 🏠 Main Next ⏩
    💬 Chat with me