Techniques for Reducing Main-Thread Work
Jul 30, 2025 am 05:33 AMMinimize and defer JavaScript by splitting code, removing unused code, and lazy-loading non-essential features; 2. Break long tasks into smaller chunks using setTimeout or requestIdleCallback to maintain responsiveness; 3. Offload heavy computation to Web Workers to free the main thread; 4. Optimize rendering by avoiding forced layouts, using efficient animations, and throttling events with requestAnimationFrame; 5. Reduce DOM size and complexity by limiting nodes and using virtualization for long lists; 6. Use efficient CSS with simple selectors and avoid expensive properties; 7. Preload critical resources and preconnect to third-party origins to reduce blocking—all to keep the main thread light, responsive, and capable of delivering fast, smooth user experiences.
Reducing main-thread work is crucial for improving web performance, especially for delivering smooth user interactions and fast load times. The main thread handles HTML parsing, JavaScript execution, layout, painting, and more—so overloading it can lead to jank, delayed responses, and poor Core Web Vitals scores. Here are practical techniques to reduce main-thread work:
1. Minimize and Defer JavaScript Execution
JavaScript is one of the biggest contributors to main-thread congestion. Every script downloaded and executed blocks the thread unless handled carefully.
-
Code splitting: Break your JavaScript into smaller chunks and load only what’s needed for the current view (e.g., using dynamic
import()
with React.lazy or webpack). -
Defer non-critical scripts: Use the
defer
attribute on<script></script>
tags so scripts run after HTML parsing. - Remove unused code: Use tree-shaking (via bundlers like Webpack or Vite) to eliminate dead code.
- Lazy-load non-essential features: Delay loading analytics, chat widgets, or heavy libraries until after the initial interaction.
Example: Instead of loading an entire charting library upfront, load it only when the user navigates to a dashboard page.
2. Optimize Long Tasks with Task Scheduling
Long-running tasks block the main thread and prevent user input from being processed. Break them into smaller chunks.
-
Use
setTimeout
orrequestIdleCallback
to yield control back to the browser:function processInChunks(items, callback) { let index = 0; function processChunk() { const end = Math.min(index 10, items.length); for (; index < end; index ) { callback(items[index]); } if (index < items.length) { setTimeout(processChunk, 0); // Yield to main thread } } processChunk(); }
requestIdleCallback
lets you run low-priority work during idle periods:requestIdleCallback(() => { // Update analytics, cache data, etc. });
This keeps the thread responsive during user interactions.
3. Leverage Web Workers for Heavy Computation
Move CPU-intensive tasks off the main thread using Web Workers.
- Use cases: image processing, large data parsing, encryption, or complex calculations.
- Workers run in the background and communicate via
postMessage
.
Example: Parsing a large JSON file or performing search indexing can be done in a worker so the UI stays responsive.
// main.js const worker = new Worker('worker.js'); worker.postMessage(data); worker.onmessage = (e) => { console.log('Result:', e.data); }; // worker.js self.onmessage = (e) => { const result = heavyComputation(e.data); self.postMessage(result); };
Note: Workers can’t access the DOM, so they’re best for pure computation.
4. Optimize Rendering and Layout
Expensive styles and layout thrashing can stall the main thread.
Avoid forced synchronous layouts:
// BAD: Forces layout element.style.height = computedHeight 'px'; const offset = element.offsetTop; // GOOD: Batch reads and writes const offset = element.offsetTop; element.style.height = offset 'px';
Use
transform
andopacity
for animations—they don’t trigger layout or paint.Debounce or throttle event handlers like
scroll
,resize
, andinput
to reduce function calls.
Example: Instead of recalculating layout on every scroll event, use
requestAnimationFrame
:let ticking = false; window.addEventListener('scroll', () => { if (!ticking) { requestAnimationFrame(() => { // Handle scroll logic ticking = false; }); ticking = true; } });
5. Reduce DOM Size and Complexity
Large DOM trees increase parsing and layout time.
- Keep the DOM lean: avoid deeply nested structures.
- Limit the number of DOM nodes (ideally under 1,500 per page).
- Use virtualization for long lists (e.g.,
react-window
orvue-virtual-scroller
) so only visible items are rendered.Example: A table with 10,000 rows should only render ~10–20 visible rows at a time, not all at once.
6. Use Efficient CSS Selectors and Avoid Expensive Properties
Complex CSS selectors and properties can slow down style calculation and painting.
- Avoid deep nesting and overly specific selectors (e.g.,
div ul li a strong
).- Minimize use of
@import
, which blocks CSS parsing.- Steer clear of properties that trigger repaints or layout (e.g.,
box-shadow
on many elements).Instead:
- Use class-based styling.
- Limit the scope of CSS with frameworks like CSS-in-JS or Shadow DOM.
7. Preload and Prioritize Critical Resources
Reduce blocking time during initial load.
- Use
rel="preload"
for critical fonts, scripts, or assets.- Preconnect to third-party origins:
<link rel="preconnect" href="https://cdn.example.com">
.- Load non-critical CSS asynchronously (e.g., with
rel="preload"
onload
swap).This ensures the main thread isn’t waiting on network delays.
Reducing main-thread work isn’t about eliminating JavaScript—it’s about smart scheduling, offloading, and optimizing how and when work happens. Focus on chunking tasks, using workers, and simplifying rendering. The result? Faster loads, smoother interactions, and a better user experience.
Basically, keep the main thread light and responsive—it’s the key to a fast-feeling app.
The above is the detailed content of Techniques for Reducing Main-Thread Work. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Many users are curious about the next-generation brand new RTX5090 graphics card. They don’t know how much the performance of this graphics card has been improved compared to the previous generation. Judging from the current information, the overall performance of this graphics card is still very good. Is the performance improvement of RTX5090 obvious? Answer: It is still very obvious. 1. This graphics card has an acceleration frequency beyond the limit, up to 3GHz, and is also equipped with 192 streaming multiprocessors (SM), which may even generate up to 520W of power. 2. According to the latest news from RedGamingTech, NVIDIARTX5090 is expected to exceed the 3GHz clock frequency, which will undoubtedly play a greater role in performing difficult graphics operations and calculations, providing smoother and more realistic games.

How to optimize and adjust the kernel parameters of Linux systems to improve performance and stability Summary: Linux is an operating system widely used in various servers and workstations, and the optimization of its performance and stability is crucial to providing efficient and reliable services. This article will introduce how to improve system performance and stability by optimizing and adjusting the kernel parameters of the Linux system. Keywords: Linux system, kernel parameters, performance optimization, stability Introduction: Linux, as an open source operating system, is widely used in various servers and work

How to use PyPy to improve the performance of Python programs Introduction: Python, as a high-level programming language, is simple, easy to read, and easy to learn, so it has been widely used. However, Python also has the problem of slow running speed due to its interpreted execution characteristics. To solve this problem, PyPy came into being. This article will introduce how to use PyPy to improve the performance of Python programs. 1. What is PyPy? PyPy is a just-in-time compiled Python interpreter

How to improve database read and write performance through PHP multi-threading. With the rapid development of the Internet, database read and write performance has become a key issue. When our application needs to frequently read and write to the database, using a single-threaded approach often leads to performance bottlenecks. The use of multi-threading can improve the efficiency of database reading and writing, thereby improving overall performance. As a commonly used server-side scripting language, PHP has flexible syntax and powerful database operation capabilities. This article will introduce how to use PHP multi-threading technology to improve

PHP8's JIT accelerator: ushering in a new era of performance improvement With the development of the Internet and the advancement of technology, the response speed of web pages has become one of the important indicators of user experience. As a widely used server-side scripting language, PHP has always been loved by developers for its simplicity, ease of learning and powerful functions. However, when processing large and complex business logic, PHP's performance often encounters bottlenecks. To solve this problem, PHP8 introduces a brand new feature: JIT (just in time compilation) accelerator. JIT accelerator is PHP8

Presumably everyone's computer system has been updated to win11, so what are the advantages and disadvantages of win11 system compared to win10 system? This is what everyone wants to know. Let's take a look at the specific advantages and disadvantages together. What are the advantages of win11 over win10: 1. Smoothness. Win11 is better than win10 in terms of single-threaded and multi-threaded 3D operation. However, the response speed of win11 is relatively slow, and you need to wait for a while after clicking. 2. The performance of games is better than win10, and the average frame rate is also better than win10. However, the memory optimization is poor, the memory and CPU consumption are much higher than win10.3, and the operation interface uses too many rounded corners. Desktop ui mining

In-depth analysis of PHP8.3: Performance improvement and optimization strategies With the rapid development of Internet technology, PHP, as a very popular server-side programming language, is also constantly evolving and optimizing. The recently released PHP 8.3 version introduces a series of new features and performance optimizations, making PHP even better in terms of execution efficiency and resource utilization. This article will provide an in-depth analysis of the performance improvement and optimization strategies of PHP8.3. First of all, PHP8.3 has made great improvements in performance. The most striking of these is JIT (JIT

How to use PHP-FPM optimization to improve the performance of Laravel applications Overview: Laravel is a popular PHP framework that adopts modern design concepts and elegant syntax to enable developers to build web applications efficiently. However, performance issues may arise when handling a large number of concurrent requests. This article will introduce how to use PHP-FPM to optimize and improve the performance of Laravel applications. 1. What is PHP-FPM? PHP-FPM (FastCGIProce
