The Browser's Main Thread Is Expensive
When you hear "frontend optimization," many people think of reducing network requests, shrinking the bundle, and utilizing caching. However, the main thread often goes unnoticed until it becomes a problem. On screens with a lot of interaction, such as live data streams and scrolling, the main thread can become a bottleneck. Even with reduced network and bundle sizes, the screen freezes when the main thread is blocked.
Users may experience stuttering scrolling, delayed button responses, or delayed typing in a search box. This jank is what occurs when the main thread is blocked.
The browser has several threads, but most of our code interacts with the main thread, which handles computation, rendering, event handling, network response handling, and framework internals. The main thread is expensive, and when it's slow, it leads to a frozen screen. The main thread is responsible for running JavaScript and drawing the screen.
JavaScript tasks execute whenever there's a gap in the queue, regardless of the screen refresh cycle. Drawing the screen involves several steps, with the final compositing step being handed off to the compositor thread. The screen needs to be redrawn at the display's refresh rate, usually 60 times per second (16.6 milliseconds per frame) for a 60Hz display.
However, the main thread processes tasks sequentially, and if one JavaScript function runs for 200 milliseconds, the browser can't repaint the screen or receive user input during that time. Tasks that take over 50 milliseconds to complete are considered a problem. The demo shows that pressing a button can block the main thread, freezing the screen, while CSS animations continue to run smoothly.
Performance optimization involves careful use of this single thread. There are two main approaches: optimizing within the main thread and offloading work to other threads. Within the main thread, there are four core techniques: splitting, batching, prioritizing, and deferring. Splitting tasks into smaller, manageable chunks is crucial for efficient execution.
Written by urgent.news from Hacker News's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.