What are Web Workers?
Learn to offload heavy work to a background thread with Web Workers.
What are Web Workers?
A Web Worker runs JavaScript in a separate background thread, away from the main thread. Normally all JavaScript runs on a single thread; a long task blocks the main thread and the page freezes.
A worker offloads heavy computations to the background and keeps the main thread free. The user interface stays smooth and buttons remain clickable. The worker and the main thread communicate only by messaging; memory is not shared directly.
Worker scope
A worker runs in its own global scope (worker scope); it cannot access the window object. Instead, the self keyword gives the worker's global object.
From inside a worker, some browser APIs like document, localStorage or console are unavailable. But APIs like fetch, IndexedDB and setTimeout do run in a worker. Touching the DOM is forbidden; only the main thread updates the UI.
Exercise Detect Web Worker support
Check whether 'Worker' exists on window using the in operator. If missing, log 'unsupported' with console.log; otherwise log 'supported'.
Show example solution
if (!('Worker' in window)) {
console.log('unsupported');
} else {
console.log('supported');
}
Test yourself
-
What does a Web Worker do?
- It runs heavy work in a background thread without blocking the main thread
- It selects all HTML elements on the page
- It fetches data from the server
- It changes CSS styles
Show answer
It runs heavy work in a background thread without blocking the main thread — Correct! The worker runs heavy computation in the background; the main thread stays free.
-
Worker vs main thread
- window
- main thread global
- self
- worker global
- document
- main thread only
- postMessage
- both sides
-
Create a worker
const worker = new ____('sorter.js');Show answer
const worker = new Worker('sorter.js');