Tutorials JavaScript Web Workers
Ch 59 / 78
Chapter 59 Advanced 8 min read JavaScript

JavaScript Web Workers

JavaScript is single-threaded — but Web Workers let you run scripts in true background threads. Offload heavy computation, keep your UI butter-smooth, and communicate safely between threads using postMessage.

What you'll learn
What Web Workers are and why they exist
How the main thread and worker communicate
Creating and terminating Dedicated Workers
Using Shared Workers and Service Workers
Transferable objects for zero-copy data transfer
Real-world use cases and limitations

What are Web Workers?

JavaScript runs on a single thread — the main thread. This means long-running tasks (image processing, complex calculations, large data parsing) block the UI, causing the page to freeze or stutter.

Web Workers are a browser API that allows you to run a JavaScript file in a separate background thread, completely independent from the main thread. The UI stays responsive while the worker crunches data in the background.

Key Idea
Workers have no access to the DOM. They can only communicate with the main thread via postMessage() and onmessage events. This design prevents race conditions.
Main Thread
Runs your page UI, DOM updates, event listeners — stays responsive at all times.
Worker Thread
Runs a separate JS file in the background — no DOM access, heavy computation safe here.
postMessage()
The only bridge between threads — sends a copy (structured clone) of the data.
onmessage
Event handler on both sides that fires when a message arrives.

How Main Thread ↔ Worker Communication Works

Both the main thread and the worker use postMessage() to send data and onmessage (or addEventListener('message', ...)) to receive it. Data is copied (structured clone algorithm), not shared.

Main Thread
UI · DOM · Events
postMessage(data)
Worker Thread
Heavy compute · No DOM
postMessage(result)
Main Thread
Receives result
main.js — Main Thread
// 1. Create a new worker from a separate JS file
const worker = new Worker('worker.js');

// 2. Send a message TO the worker
worker.postMessage({ task: 'compute', value: 1_000_000 });

// 3. Listen for messages FROM the worker
worker.onmessage = (event) => {
  console.log('Result from worker:', event.data);
};

// 4. Handle errors in the worker
worker.onerror = (err) => {
  console.error('Worker error:', err.message);
};
worker.js — Worker Thread
// worker.js — this file runs in a background thread

// Listen for messages from the main thread
self.onmessage = (event) => {
  const { task, value } = event.data;

  if (task === 'compute') {
    let sum = 0;
    for (let i = 1; i <= value; i++) {
      sum += i;
    }
    // Send result back to the main thread
    self.postMessage({ result: sum });
  }
};

Types of Web Workers

There are three main types of Web Workers, each suited to different scenarios:

Dedicated Worker
The most common type. Only the page that created it can communicate with it. Created with new Worker('file.js').
Shared Worker
Shared across multiple pages, tabs, or iframes from the same origin. Uses new SharedWorker('file.js') and a port for communication.
Service Worker
Acts as a programmable network proxy. Powers offline caching, push notifications, and background sync. Part of Progressive Web Apps (PWA).
Feature Dedicated Worker Shared Worker Service Worker
Scope One page only Multiple tabs/pages Whole origin
Primary Use Heavy compute Shared state/data Caching, push, offline
DOM Access
No
No
No
Intercept Network
No
No
Yes
Persistent
No
No
Yes
⚡
Free Resource
Download our JavaScript Cheat Sheet
Syntax, built-in methods, ES6+ features — all on one page.
Get Sheet

Dedicated Worker — Complete Example

Here is a full working example using a Dedicated Worker to find all prime numbers up to N — a CPU-intensive task that would freeze the UI if run on the main thread.

index.html — Main Thread
<!DOCTYPE html>
<html><body>
  <h2>Prime Number Finder</h2>
  <input type="number" id="limit" value="1000000">
  <button onclick="startWorker()">Find Primes</button>
  <p id="status">Idle</p>

  <script>
    let worker;

    function startWorker() {
      // Terminate any existing worker first
      if (worker) worker.terminate();

      worker = new Worker('primes-worker.js');
      const limit = +document.getElementById('limit').value;

      document.getElementById('status').textContent = '⏳ Working...';
      worker.postMessage(limit);

      worker.onmessage = ({ data }) => {
        document.getElementById('status').textContent =
          `✅ Found ` + data.count + ` primes in ` + data.ms + `ms`;
      };
    }
  </script>
</body></html>
primes-worker.js — Worker Thread
// Sieve of Eratosthenes — runs in background thread
self.onmessage = ({ data: limit }) => {
  const start = Date.now();
  const sieve = new Uint8Array(limit + 1).fill(1);
  sieve[0] = sieve[1] = 0;

  for (let i = 2; i * i <= limit; i++) {
    if (sieve[i]) {
      for (let j = i * i; j <= limit; j += i) {
        sieve[j] = 0;
      }
    }
  }

  const count = sieve.reduce((acc, v) => acc + v, 0);
  self.postMessage({ count, ms: Date.now() - start });
};
Pro Tip
Use worker.terminate() to stop a worker immediately when it is no longer needed — this frees up the background thread and its memory.

Inline Workers with Blob URLs

Workers normally require a separate file, but you can create an inline worker using a Blob URL — great for prototyping or self-contained scripts.

JS — Inline Worker via Blob
// Define the worker code as a string
const workerCode = `
  self.onmessage = ({ data }) => {
    const result = data.map(n => n * 2);
    self.postMessage(result);
  };
`;

// Create a Blob URL from the string
const blob = new Blob([workerCode], { type: 'application/javascript' });
const blobURL = URL.createObjectURL(blob);

// Spawn the worker
const worker = new Worker(blobURL);
worker.postMessage([1, 2, 3, 4, 5]);

worker.onmessage = ({ data }) => {
  console.log(data); // [2, 4, 6, 8, 10]
  URL.revokeObjectURL(blobURL); // free memory
  worker.terminate();
};

Transferable Objects — Zero-Copy Transfer

By default, postMessage() uses the structured clone algorithm — it copies the data. For large buffers (like ArrayBuffer), this is expensive.

Transferable objects are transferred (ownership moved) rather than copied — the sender loses access and the receiver gets it instantly, with zero serialisation cost.

JS — Transferable ArrayBuffer
// Allocate a large 32 MB buffer
const buffer = new ArrayBuffer(32 * 1024 * 1024);

console.log('Before transfer:', buffer.byteLength); // 33554432

// Transfer (not copy) the buffer to the worker
worker.postMessage({ buffer }, [buffer]);

console.log('After transfer:', buffer.byteLength); // 0 — main thread no longer owns it
Transferable Types
Objects that can be transferred: ArrayBuffer, MessagePort, ImageBitmap, OffscreenCanvas. Regular objects and arrays are always cloned.

What Workers Can & Cannot Do

Workers run in a restricted but capable environment. Knowing what is and isn't available helps you design your architecture correctly.

✅
Workers CAN do
  • Use fetch() & XMLHttpRequest
  • Use setTimeout / setInterval
  • Use WebSockets
  • Import scripts with importScripts()
  • Use IndexedDB
  • Use crypto, performance
  • Use ES Modules (type: 'module')
❌
Workers CANNOT do
  • Access the DOM
  • Access window object
  • Access document
  • Directly manipulate localStorage
  • Use alert() / confirm()
  • Share variables with main thread directly

Real-World Use Cases

Web Workers shine in scenarios where blocking the main thread would ruin the user experience:

Data Visualisation
Image Processing
ML Inference
Text Parsing & Search
File Compression
Encryption / Hashing
Large Dataset Sort
Game Physics / AI
Advertisement

Try It Yourself

Live Editor
✎ Editor
👁 Preview
Common Mistake
Workers only load from the same origin as the page (CORS restrictions apply strictly). If you get a SecurityError, check that your worker file is served from the same domain. Use Blob URLs for inline workers to sidestep this during development.
Quick Check — Chapter 59

Which method is used to send data from the main thread to a Web Worker?

Chapter Summary
  • Web Workers let you run JavaScript in a true background thread, keeping the main thread and UI responsive.
  • Communication happens exclusively via postMessage() and onmessage — data is copied using the structured clone algorithm.
  • The three types are: Dedicated Worker (one page), Shared Worker (multiple tabs), and Service Worker (network proxy + offline).
  • Workers have no access to the DOM, window, or document, but can use fetch, IndexedDB, and WebSockets.
  • Use Transferable objects (like ArrayBuffer) to transfer large data buffers with zero copy cost.
  • Always call worker.terminate() when finished to free up memory and the background thread.

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel