Web Workers: Definition, Use Cases, Examples

A Web Worker runs JavaScript on a background thread so the page stays responsive. How it works, what it cannot do, and when it is worth using.

What is a Web Worker?

A Web Worker is a JavaScript file that the browser runs on a background thread, separate from the main thread that handles rendering and user input. MDN describes it as a way to run scripts in background threads without interfering with the user interface. Moving heavy work there keeps the page responsive, which helps metrics like Interaction to Next Paint (INP).

How Web Workers work

The page creates a worker with new Worker("worker.js"). The two sides cannot share variables: they talk by sending messages with postMessage and receiving them in a message event. A worker has no access to the DOM or to the page's objects, so it cannot touch what the user sees. It sends results back and the main thread updates the page.

// main.js
const worker = new Worker('worker.js');
worker.postMessage({ rows: largeArray });
worker.addEventListener('message', (event) => {
  console.log('Result:', event.data);
});

// worker.js
self.addEventListener('message', (event) => {
  const result = expensiveCompute(event.data.rows);
  self.postMessage(result);
});

Types of workers

TypeWhat it is for
Dedicated workerUsed only by the script that created it. The common choice.
Shared workerReachable from several scripts, tabs or frames of the same origin, through a port.
Service workerA proxy between the page, the browser and the network, for offline use, caching, push and background sync. See service workers.
WorkletA lightweight worker for a specific job, such as the Audio Worklet for audio processing.

What a worker can and cannot do

Workers can use fetch, WebSockets, IndexedDB and timers, and they can load scripts with importScripts(). They cannot manipulate the DOM or use parts of window; use self instead. localStorage is a window feature and is not exposed in workers, so use IndexedDB for storage there. Check the MDN guide to using web workers and its list of available functions before you rely on an API.

When a Web Worker is worth it

  • Long tasks. A task that runs on the main thread for more than 50 ms counts as a long task, according to web.dev. Work that regularly crosses that line is a candidate.
  • Parsing and transforming large data, such as big JSON, CSV or XML files.
  • Cryptography and hashing that would otherwise freeze the interface.
  • Image, audio and document processing, such as resizing, compressing or OCR.
  • Background fetching and syncing while the user keeps working.

Passing data efficiently

Messages are copied by default, using structured cloning. For big payloads that copy is the real cost. Transferable objects such as an ArrayBuffer move to the other side with a zero-copy transfer, and the original becomes unusable:

const bytes = new Uint8Array(1024 * 1024 * 32);
worker.postMessage(bytes.buffer, [bytes.buffer]);

SharedArrayBuffer lets threads use the same memory, but MDN flags determinism, security and performance concerns, so reach for it only when you need it. When a worker is done, call worker.terminate() from the main thread to stop it immediately.

Example: a laggy CSV import

A dashboard parses a large CSV when the user drops it on the page. On the main thread the page freezes for seconds, clicks queue up and INP is poor. Moving the parser into a worker and sending back parsed chunks keeps the interface moving and lets you show a progress bar. The parse takes the same time, but the user can keep interacting while it runs.

Common mistakes

  • Posting huge objects repeatedly. Cloning costs time and memory. Transfer buffers or send smaller chunks.
  • Trying to touch the DOM from the worker. It throws. Send data back and update the page on the main thread.
  • Creating a worker per click. Start-up has a cost. Reuse a worker or a small pool.
  • Forgetting to terminate. Idle workers keep memory. Call terminate() or let the worker close itself.
  • Adding a worker for tiny tasks. Below the long-task threshold the messaging overhead usually outweighs the gain.
  • Ignoring errors. Listen for the worker's error event, or failures stay silent.

Web Workers, performance testing and monitoring

Workers help front-end responsiveness, so measure it. web.dev describes Total Blocking Time (TBT) as a lab metric that often correlates with a low INP, and recommends aiming for under 200 ms on average mobile hardware. INP itself is a field metric: web.dev rates 200 ms or less at the 75th percentile as good. LoadFocus page speed monitoring runs Lighthouse from several locations so you can watch lab results over time, and the free Core Web Vitals checker shows real-user INP from Chrome UX Report data, with no signup. For wider context, see Core Web Vitals and mastering JavaScript for performance. Load testing, in contrast, exercises your servers; it will not show you main-thread blocking in the browser.

FAQ: Web Workers

What is the difference between a Web Worker and a Service Worker?

A Web Worker runs general JavaScript in the background for a page. A service worker sits between the page and the network and handles caching, offline use, push and background sync.

Can a Web Worker access the DOM?

No. Workers run in their own context without the DOM. They send results with postMessage and the main thread updates the page.

Do Web Workers make code run faster?

Not by themselves. The computation takes about the same time, but it no longer blocks the interface. Splitting work across several workers can also finish it sooner on multi-core devices.

How do workers share data?

By message passing, which copies data, by transferring objects like an ArrayBuffer, or by using a SharedArrayBuffer where its security requirements are met.

Do I need a Web Worker for my app?

Only if CPU-heavy work blocks the main thread. Most pages do not need one; those that do see a clear gain in responsiveness.

How fast is your website?

Elevate its speed and SEO seamlessly with our Free Speed Test.

Free Website Speed Test

Analyze your website's load speed and improve its performance with our free page speed checker.