Skip to main content

What does a Web Worker do?

What a Web Worker is

A Web Worker is a separate thread for running JavaScript code, working in parallel with the main thread (the UI thread).

It does not block the interface and can run heavy computations, then pass the result back to the main thread.

The problem without a Web Worker

JavaScript in the browser is single-threaded - everything runs in one thread:

  • page rendering
  • event handling
  • running your code

If you run a heavy loop in that thread:

javascript
for (let i = 0; i < 1e9; i++) {} console.log('Done!');

the page will "freeze" - the interface stops responding until the loop finishes, because the Event Loop is busy.

The solution - a Web Worker

With a Web Worker you can move that computation into a separate thread:

javascript
// main.js const worker = new Worker('worker.js'); worker.postMessage(1e9); // send the task worker.onmessage = (event) => { console.log('Result:', event.data); };
javascript
// worker.js onmessage = (event) => { let sum = 0; for (let i = 0; i < event.data; i++) sum += i; postMessage(sum); // send the result back };

Now the heavy computation runs in the background, and the UI stays responsive.

How it works under the hood

  1. The main thread creates a worker via new Worker('script.js').
  2. The browser starts a separate JS thread.
  3. Communication between threads happens through messages (message passing).
  4. The transfer is asynchronous, data is serialized (structured clone).
  5. The worker does not have access to the DOM, window, or document.

Exchanging data (message passing)

Communication happens through the postMessage and onmessage events:

javascript
// main.js worker.postMessage({ action: 'sum', a: 5, b: 7 }); // worker.js onmessage = (e) => { if (e.data.action === 'sum') { postMessage(e.data.a + e.data.b); } };

You can pass:

  • strings, numbers, objects
  • ArrayBuffer, Blob, File, ImageBitmap
  • even Transferable objects, to pass data without copying it

One-sided limitations

A Web Worker is isolated:

  • no access to document, window, alert(), localStorage
  • has access to: fetch, XMLHttpRequest, WebSocket, setTimeout, indexedDB, crypto, etc.

Types of Web Workers

TypeWhere it is usedFeatures
Dedicated WorkerOne per oneWorks only with the script that created it
Shared WorkerSeveral tabs/scriptsOne worker for all pages (by origin + URL)
Service WorkerBetween the browser and the networkCaches requests, works even offline

Shared Worker example

javascript
// shared-worker.js onconnect = (event) => { const port = event.ports[0]; port.onmessage = (e) => { port.postMessage(`Received: ${e.data}`); }; };

Several tabs can connect to the same Shared Worker - for example, to exchange data between tabs.

Service Worker (a special type)

A Service Worker is not just a thread, it's a "proxy" between the browser and the network.

It intercepts HTTP requests, caches responses, and lets an app work offline. (Example: PWA apps, push notifications, background sync.)

Service Worker example

javascript
// service-worker.js self.addEventListener('fetch', (event) => { event.respondWith( caches.match(event.request).then((cached) => { return cached || fetch(event.request); }) ); });

This means: if there is a cached response, return it, otherwise load it from the network and save it.

Streaming data processing in a worker

A worker can use the Streams and Fetch APIs:

javascript
onmessage = async (e) => { const response = await fetch(e.data.url); const text = await response.text(); postMessage(text.length); };

This way you can process network data in the background, without blocking the UI at all.

"Parallel" computation example

javascript
const workers = Array.from({ length: 4 }, () => new Worker('calc.js')); let completed = 0; let result = 0; workers.forEach((w, i) => { w.postMessage(i); w.onmessage = (e) => { result += e.data; if (++completed === 4) console.log('Done:', result); }; });

This way computation can be distributed across several threads ("pseudo-parallelism").

When to use Web Workers

ScenarioWhy it's useful
Complex computationsJSON parsing, cryptography, machine learning
Processing large datafiltering/aggregating arrays, processing CSV
Working with imagescompression, filters, thumbnail generation
Games / animationphysics calculations without interface lag
WebSocket + data analysisstreaming processing

A simple analogy

Imagine the browser is a kitchen.

  • The main thread (the main JS) is the chef who cooks the dish and serves the guests.
  • The Web Worker is an assistant at another station who chops vegetables.

The chef gives a task -> the assistant does it in the background -> returns the result. No one gets in anyone's way.

Summary

ComponentWhat it does
Web WorkerA separate thread for running code
Main advantageDoes not block the UI
Data exchangeThrough postMessage / onmessage
LimitationsNo access to the DOM, window, document
TypesDedicated, Shared, Service Worker
Main usesBackground computation, caching, offline mode, synchronization

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.