Web Workers: Definition, Use Cases, Performance Examples

Web Workers run JavaScript on background threads — keeps the main thread responsive. For heavy compute, parsing, encryption, WebAssembly.

What is a Web Worker?

A Web Worker is a JavaScript script that runs on a separate thread from the main UI thread, in the background. By offloading expensive work (image processing, parsing, cryptography, complex computations) to a Web Worker, you keep the main thread free to handle user input, animations, and rendering — preserving responsiveness and improving Core Web Vitals like INP.

Web Workers were introduced in 2009 with HTML5 and are supported in all modern browsers. They communicate with the main thread via message passing — workers can't access the DOM directly.

Types of Web Workers

TypeUse case
Dedicated WorkerOne worker per page; most common
Shared WorkerShared across multiple tabs/windows of same origin
Service WorkerNetwork proxy for offline / caching / push notifications
Worklet (Audio/Paint/Layout)Specialized workers for low-level browser features

Basic Web Worker example

// main.js
const worker = new Worker('worker.js');

worker.postMessage({ task: 'compute', data: largeArray });

worker.addEventListener('message', (event) => {
  console.log('Result:', event.data);
});

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

What Web Workers can do

  • Heavy computation (data processing, cryptography, image manipulation)
  • Parsing large JSON/XML/CSV
  • Background sync
  • Run WebAssembly modules
  • Use IndexedDB, fetch, WebSocket, Cache API
  • Use most JS APIs except DOM

What Web Workers can NOT do

  • Access the DOM
  • Use window, document objects
  • Use synchronous XHR (use fetch/IndexedDB instead)
  • Access localStorage (use postMessage from main thread)

When to use a Web Worker

  • Long-running computation. Anything > 50ms blocking the main thread.
  • Real-time data processing. Streaming, video frame analysis.
  • Cryptography. Encryption/hashing without UI freeze.
  • Image/PDF processing. Resize, OCR, etc.
  • Background fetching/syncing.
  • Running WebAssembly modules.

Service Worker: a special kind of worker

Service Workers act as a proxy between the browser and the network. They enable:

  • Offline support. Serve cached resources when network unavailable.
  • Push notifications. Receive server pushes even when site is closed.
  • Background sync. Defer requests until user is online.
  • Advanced caching. Cache strategies (cache-first, network-first, stale-while-revalidate).
  • PWA foundation. Required for Progressive Web Apps.

Service Worker example

// register from main.js
navigator.serviceWorker.register('/sw.js');

// sw.js
self.addEventListener('install', (event) => {
  event.waitUntil(
    caches.open('v1').then((cache) => cache.addAll(['/', '/styles.css']))
  );
});

self.addEventListener('fetch', (event) => {
  event.respondWith(
    caches.match(event.request).then((response) => response || fetch(event.request))
  );
});

Web Worker performance impact

Without Workers, heavy JS work blocks the main thread, causing:

  • Bad INP (interactions feel sluggish)
  • Janky scrolling
  • Frozen UI
  • Browser "page is unresponsive" warning

With Workers, the work runs in parallel; UI stays at 60fps. Major impact on user experience and Core Web Vitals.

Web Worker best practices

  • Use for long tasks. Anything > 50ms blocking is a candidate.
  • Minimize message passing overhead. Each postMessage serializes data; large payloads slow.
  • Use Transferable Objects. ArrayBuffer + transfer = zero-copy.
  • Worker pool for parallelism. N workers for N tasks; reuse vs spawn-per-task.
  • Terminate when done. worker.terminate() frees memory.
  • Handle errors. worker.onerror + try/catch inside worker.
  • Bundle worker code. Use Vite/webpack worker plugins for ergonomics.

Common pitfalls

  • Sending huge data in messages. postMessage clones — slow. Use Transferables.
  • Trying to access DOM from worker. Throws — workers have no DOM.
  • Forgetting to terminate. Leaks memory; orphan workers persist.
  • Over-engineering. Adding workers for tasks < 16ms is unnecessary overhead.
  • Worker startup cost. Spinning up workers per click is slow; use a pool.
  • Not handling worker errors. Silent failures.
  • Using sync APIs in worker. Sync XHR, sync fs not allowed.

Web Worker libraries / patterns

LibraryPurpose
ComlinkRPC-style API over postMessage
WorkerizeWebpack loader for worker functions
Threads.jsWorker pool + observable patterns
Vite Worker importBuilt-in worker support in Vite
WorkboxGoogle library for Service Worker patterns

FAQ: Web Workers

Web Worker vs Service Worker: what's the difference?

Web Worker: general background JS execution. Service Worker: network proxy for caching, offline, push notifications.

Can Web Workers access the DOM?

No. They run in their own context with no DOM access. Use postMessage to send data back to the main thread.

Are Web Workers slow to start up?

~10-50ms to spawn. For frequent short tasks, use a worker pool (workers spawned at app start, reused).

How do I share state between workers?

SharedArrayBuffer (with Cross-Origin headers) for shared memory. Otherwise, message passing.

Can I run npm packages in a Web Worker?

Yes — bundle them via Webpack/Vite worker imports.

What's a Worklet?

A specialized lightweight worker for low-level browser APIs (Audio Worklet, Paint Worklet, Layout Worklet, Animation Worklet).

Are Web Workers necessary for my app?

Only if you have CPU-bound work blocking the main thread. Most apps don't need them; those that do benefit dramatically.

Test Web Worker performance with LoadFocus

LoadFocus runs Lighthouse audits from 25+ regions, measuring INP and main-thread blocking — the metrics Web Workers help. Sign up free at loadfocus.com/signup.

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.

×