Skip to content
jshacks.dev
Browser

How the Browser Runs JavaScript: Parse, Execute, Render

Follow a script through the browser: the HTML parser, fetching, V8 compiling, the event loop, microtasks and rendering, with the console output in order.

6 min read
Summarize in AI
Flat illustration of a browser and a server trading a request and a response, with the JavaScript, Google Chrome and Postman logos.

When a page loads, three jobs share one thread: parsing HTML, running JavaScript, and painting the result. Most of the confusing behavior people meet in the browser, from a script that cannot find an element to a button that freezes the page, comes from how those three jobs take turns. This post follows a script from the network to the screen in current Chrome, Firefox and Safari: how the parser meets a <script>, what the JavaScript engine does with the source, how the event loop schedules callbacks, and when the browser renders. The specifications are the HTML Standard's parsing section and its event loop processing model.

The main thread does everything

A page has one main thread, which runs your JavaScript, builds the DOM, calculates styles and layout, handles input events and paints. Work from these categories cannot overlap on that thread. A long-running function blocks everything else: no clicks are handled, no animation frames run and no text appears until it returns. Workers run on other threads, and the compositor and network stack are separate, but anything that touches the DOM runs on the main thread.

That single fact explains the rest of the post. The browser interleaves tasks on one thread, and your job is to keep each piece short.

Parsing the HTML

The parser reads bytes, decodes them to characters, tokenizes them and builds the DOM tree incrementally. It does not wait for the full document: it builds as bytes arrive, and the browser can paint early parts of the page before the end arrives.

A <script> tag interrupts that. A classic script with no attributes is parser-blocking: the parser stops, fetches the file if it is external, runs it, and only then continues. The reason is that the script may call document.write, which inserts text into the stream the parser is reading, so the parser cannot proceed until it knows.

order.htmlHTML
<p id="first">First</p>
<script>
  console.log("count at script:", document.querySelectorAll("p").length);
</script>
<p id="second">Second</p>
Text
count at script: 1

At the moment the script runs, the parser has built only the first paragraph, so the count is 1. The second paragraph does not exist yet. This is why a script in <head> that reads the page cannot find elements: the DOM is empty when it runs. Moving the script to the end of <body>, or using defer, fixes it. The attributes that change this behavior, async, defer and type="module", have their own post.

Fetching and compiling

An external script is a network request, and a blocking one stalls the parser for its duration, which is why <script src> in the head hurt page speed for so long. The browser's preload scanner helps: while the main parser waits for a script, a second lightweight pass scans the remaining HTML for resources such as scripts, styles and images and starts fetching them early.

Once the source arrives, the JavaScript engine takes over. In Chrome and Node.js that engine is V8, in Firefox SpiderMonkey and in Safari JavaScriptCore. All of them follow the same broad pipeline, described in the V8 documentation. The source is parsed into an abstract syntax tree, and then into bytecode that an interpreter can run immediately. Code that runs often is detected and handed to an optimizing compiler, which produces machine code specialized for the types it has seen. If a later call breaks an assumption, such as a property that was always a number becoming a string, the engine throws away the optimized code and falls back to the interpreter, a step called deoptimization.

Engines also avoid compiling what you never call. Functions are parsed lazily, with a quick pre-parse that checks syntax and defers building bytecode until the first call. This is why shipping less JavaScript, and not just smaller JavaScript, makes a page start faster: every byte must still be downloaded, scanned and, for the code that runs, compiled.

Running the script: the call stack and the event loop

Running a script means executing its top-level statements on the call stack until the stack is empty. After that, the browser looks for the next piece of work. The event loop is the mechanism: it picks a task from a queue, runs it to completion, then does a microtask checkpoint, then possibly renders, then picks the next task.

Tasks come from several sources: running a script, a click or key event, a timer callback from setTimeout, a network response, a message from a worker. Microtasks are smaller jobs that run immediately after the current task, before anything else, and include promise reactions and queueMicrotask callbacks.

order.jsJavaScript
console.log("1 script start");

setTimeout(() => console.log("5 timeout"), 0);

Promise.resolve().then(() => console.log("3 promise"));

queueMicrotask(() => console.log("4 microtask"));

console.log("2 script end");
Text
1 script start
2 script end
3 promise
4 microtask
5 timeout

The script itself is one task: lines one and two run in order. When it finishes, the microtask queue is emptied, so the promise reaction and the queued microtask run, in the order they were queued. Only then does the loop pick the next task, the timer, which is why setTimeout(..., 0) runs after the promise. A timeout of zero means "after the current task and its microtasks", not "now".

The consequence is that microtasks can starve the loop. If a microtask keeps scheduling another microtask, the queue never empties, and the browser never reaches rendering or the next event. A loop of await calls that never yield to a task has the same effect.

When rendering happens

After a task and its microtasks, the browser decides whether to render. It aims for a frame every display refresh, 16.7 milliseconds at 60 hertz, though it may skip a frame when nothing changed. A rendering opportunity runs several steps in order: pending requestAnimationFrame callbacks, then style calculation, layout, paint and compositing.

frame.jsJavaScript
requestAnimationFrame(() => console.log("A animation frame"));
setTimeout(() => console.log("B timeout"), 0);
Promise.resolve().then(() => console.log("C promise"));
console.log("D sync");
Text
D sync
C promise
B timeout
A animation frame

The usual order is synchronous code, then microtasks, then the timer task, then the animation frame callback at the next rendering opportunity. The timer and the frame are separate steps, and in practice a frame can come before a zero-delay timer when a rendering opportunity is already due, so the relative order of B and A is not guaranteed by any specification. Code that depends on it is a bug. What the specification does guarantee is that a task runs to completion, and that microtasks run before the next task.

The practical rule is that DOM changes made in one task are batched into a single render. Changing a style ten times in a loop paints once. But reading a layout-dependent property, such as offsetHeight, after a write forces the browser to compute layout immediately, which is called a forced synchronous layout. A loop that alternates writes and reads repeats that cost for each iteration, so batch reads first, then writes.

thrash.jsJavaScript
const items = document.querySelectorAll(".item");

const heights = [];
for (const item of items) {
  heights.push(item.offsetHeight);
}

for (const [index, item] of items.entries()) {
  item.style.height = `${heights[index] + 10}px`;
}

All reads happen first, so layout is computed once, and all writes follow, so the next layout is computed once at render time.

Keeping the thread free

Three techniques keep the main thread responsive. Break long work into chunks and yield between them, with setTimeout, scheduler.yield() where supported, or requestIdleCallback for low-priority work. Move heavy computation to a Web Worker, which runs on its own thread and talks to the page through messages. And avoid work you do not need at load: defer scripts, load code on demand with dynamic import(), and keep the initial bundle small.

The browser's performance panel shows this directly. A long task appears as a block over 50 milliseconds on the main thread, and anything under it is the call tree that held it. That is where to look first when a page feels slow.

Share

Keep reading

Flat illustration of a browser and a server trading a request and a response, with the Google Chrome, Swagger, Postman and NGINX logos.
Browser

The DOM Tree: Nodes, Elements and Text

Understand the DOM tree: node types, the difference between nodes and elements, text and comment nodes, tree navigation properties and how whitespace shows up.

6 min read
Flat illustration of an editor window full of code, with the Google Chrome, JavaScript and npm logos.
Browser

script Tags: async, defer and type=module

Compare classic, async, defer and module script tags: when each downloads, when each runs, how order is kept and which one to pick for each kind of script.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.