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 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.
postMessage() and onmessage events. This design prevents race conditions.
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.
// 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 — 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:
new Worker('file.js').new SharedWorker('file.js') and a
port for communication.
| 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 |
|
|
|
| Intercept Network |
|
|
|
| Persistent |
|
|
|
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.
<!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>
// 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 });
};
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.
// 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.
// 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
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.
- Use
fetch()& XMLHttpRequest - Use
setTimeout / setInterval - Use
WebSockets - Import scripts with
importScripts() - Use
IndexedDB - Use
crypto,performance - Use ES Modules (type: 'module')
- Access the
DOM - Access
windowobject - 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:
Try It Yourself
SecurityError, check that your
worker file is served from the same domain. Use Blob URLs for inline workers to sidestep this
during development.
Which method is used to send data from the main thread to a Web Worker?
- 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, ordocument, but can usefetch, 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
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.