Skip to content
Tutorials Center
My learning

Topics

Lesson 91 of 122 Β· Web APIs

Web Workers

Keep your page responsive with Web Workers. Learn how to start a worker, exchange messages with postMessage, handle errors and stop a worker with terminate.

JavaScript in a web page runs on a single main thread. That one thread does almost everything: it runs your scripts, responds to clicks and key presses, works out the layout and paints the screen. If your code spends two seconds crunching numbers, the page spends two seconds frozen. Buttons don't respond, animations stop and typing goes nowhere.

Web Workers fix this by running a script on a separate, background thread. The worker does the heavy lifting while the main thread stays free to keep the page smooth. The two sides talk by sending messages to each other. In this lesson you will create workers, send data back and forth, handle errors, and shut workers down.

What a worker can and cannot do

A worker is a separate JavaScript environment with its own global object (self instead of window). It is deliberately isolated:

A worker can A worker cannot
Run any ordinary JavaScript: loops, math, string processing Touch the DOM (document doesn't exist)
Use fetch(), timers, WebSocket, IndexedDB Use alert() or window
Send and receive messages Use localStorage or sessionStorage
Start other workers Share variables with the page

Because a worker can't touch the page, the usual pattern is: the page sends the worker some data, the worker computes a result and sends it back, and the page updates the DOM.

Good jobs for a worker include parsing a large file, resizing or filtering an image, searching thousands of records, compressing data or running a game's physics.

Creating a worker

Usually a worker's code lives in its own file. You start it by passing that file's URL to the Worker constructor:

JavaScript
// main.js (runs on the page)
const worker = new Worker('worker.js');

worker.postMessage(42);                  // send data to the worker

worker.addEventListener('message', (event) => {
  console.log('The worker replied:', event.data);
});
JavaScript
// worker.js (runs in the background)
self.addEventListener('message', (event) => {
  const result = event.data * 2;
  self.postMessage(result);              // send the answer back
});

The pattern is symmetrical. Each side calls postMessage() to send and listens for message events to receive. The data is always in event.data.

A worker file must come from the same origin as the page. You can also create a module worker, which can use import statements, by adding an option:

JavaScript
const worker = new Worker('worker.js', { type: 'module' });

Workers without a separate file

For small demos (and the editors on this site, which have no files to load), you can build the worker's code from a string. Put the code in a Blob, turn the blob into a temporary URL with URL.createObjectURL(), and hand that URL to Worker:

JavaScript
const code = `self.onmessage = (event) => self.postMessage(event.data * 2);`;
const blob = new Blob([code], { type: 'text/javascript' });
const worker = new Worker(URL.createObjectURL(blob));

The first example below builds the worker's code from an ordinary function with countPrimes.toString(). The second keeps it in a <script type="text/plain"> element: the browser does not run scripts of unknown types, so the element simply stores the text until you read it with textContent.

Seeing the difference

The example counts prime numbers the slow way: a job that takes a second or two. The orange square is moved by JavaScript on the main thread, so it can only move when the main thread is free.

  1. Click Count on the main thread. The square freezes and the page ignores you until the work is done.
  2. Click Count in a worker. The same work runs, but the square keeps moving the whole time.
Main thread versus worker

The worker is not faster; the work takes about the same time either way. What changes is that the page stays responsive while it runs. That is the whole point of workers.

Sending data: copies, not references

postMessage() doesn't share objects between threads. It makes a copy using the structured clone algorithm. That copy handles plain objects, arrays, strings, numbers, Date, Map, Set, typed arrays, Blob and File objects, and more. It cannot copy functions or DOM elements; trying throws a DataCloneError.

JavaScript
worker.postMessage({ name: 'report', created: new Date(), rows: [1, 2, 3] }); // fine
worker.postMessage({ format: (n) => n.toFixed(2) });  // DataCloneError
worker.postMessage(document.body);                    // DataCloneError

Copying a huge buffer takes time. For large binary data you can transfer it instead: ownership moves to the worker instantly, and the buffer becomes unusable on the sending side.

JavaScript
const pixels = new Uint8ClampedArray(4_000_000);
worker.postMessage(pixels.buffer, [pixels.buffer]); // transferred, not copied
console.log(pixels.byteLength);                     // 0: it now belongs to the worker

Errors and stopping workers

If code inside a worker throws and doesn't catch the error, the worker fires an error event on the Worker object in the page. The event includes a message, plus filename and lineno when available. A message that couldn't be copied fires messageerror instead.

When you no longer need a worker, stop it. There are two ways:

  • From the page, worker.terminate() kills the worker immediately, even in the middle of a loop.
  • From inside, the worker can call self.close() once it has finished.

Workers use memory and a thread, so terminate the ones you are done with. The example below starts a worker that ticks every half second, can be made to crash on purpose, and can be stopped.

Messages, errors and terminate

Notice that after a crash the ticks keep coming. An uncaught error in a message handler doesn't stop the worker; it just reports the error. Only terminate() (or self.close()) ends it for good.

console.log() inside a worker prints to the browser's real DevTools console, not to the console panel under these editors. Use postMessage() to send anything you want to see on the page.

Other kinds of workers

What you built here are dedicated workers: each belongs to the page that created it. You may come across two relatives:

  • Shared workers (new SharedWorker(url)) can be used by several tabs of the same origin at once, for example to share one connection between them.
  • Service workers sit between your site and the network. They power offline support, caching and push notifications. They need HTTPS and have their own lifecycle, which makes them a topic of their own.

Check your understanding

Quick check Β· 5 questions

of 5 answered You scored / 5 Β· perfect!

  1. 1. What is the main benefit of moving a heavy calculation into a Web Worker?

    The work takes about as long, but it runs on a background thread, so clicks, typing and animations on the main thread keep working.
  2. 2. Inside a worker, you write document.querySelector('#result'). What happens?

    Workers can't access the DOM, so document is not defined there. Send the result to the page with postMessage() and update the DOM there.
  3. 3. How does a worker send a result back to the page?

    Both sides communicate with postMessage(). The page receives the value in event.data of a message event.
  4. 4. You post an object that contains a function to a worker. What happens?

    Messages are copied with the structured clone algorithm, which supports data such as objects, arrays, dates and maps, but not functions or DOM nodes.
  5. 5. Which call stops a running worker immediately from the page?

    terminate() kills the worker at once. close() is called from inside the worker as self.close(), and a 'stop' message only works if your worker code handles it.

Summary

  • Heavy JavaScript on the main thread freezes the page; a Web Worker runs it on a background thread.
  • Start a worker with new Worker(url) (add { type: 'module' } for module workers); for quick demos, use a Blob URL.
  • Both sides use postMessage() to send and the message event to receive; data arrives in event.data.
  • Messages are copied with structured clone. Functions and DOM nodes can't be sent; large buffers can be transferred.
  • Workers have no DOM, window or Web Storage, but they can use fetch(), timers and IndexedDB.
  • Handle the error event, and stop workers with terminate() or self.close().

Next lesson: Server-Sent Events, where a server pushes live updates to your page over a single long-lived connection.