Web Workers: Running JavaScript in Background Threads
Web Worker is mechanism in JavaScript that allows running background thread to execute heavy or long operations without blocking main UI.
With Web Workers you can:
- perform complex calculations,
- process large data arrays,
- work with canvas or WebAssembly,
- and not freeze interface.
What Can't Web Worker Do?
- Has no access to DOM
- Can't access
window,document,alert,localStorage - Can work only through messages (message passing)
Example: Creating Web Worker
worker.js — Worker Script
// worker.js
self.onmessage = function (e) {
const result = e.data * 2;
postMessage(result); // send answer back
};
main.js — Main Script
// main.js
const worker = new Worker('worker.js');
worker.onmessage = function (e) {
console.log('Answer from worker:', e.data);
};
worker.postMessage(21); // Send data to worker
In this example 21 is sent to worker, it processes and returns 42.
Web Workers Advantages
- Asynchrony: heavy tasks execute without freezing interface
- Performance: can parallelize data processing
- Message exchange: simple API via postMessage
Web Workers API
| Method/Event | Purpose |
|---|---|
new Worker(url) | Creating worker |
worker.postMessage() | Sending data to worker |
worker.onmessage | Receiving data from worker |
worker.terminate() | Forced worker stop |
self.onmessage | Handling incoming data inside worker |
postMessage() | Sending answer from worker to main thread |
Where to Apply Web Workers?
- Processing large data arrays
- Graphics generation, rendering
- Image compression
- Cryptography
- Parsing large JSON/CSV
- Machine Learning in browser (via WebAssembly + Worker)
Cons and Limitations
- Debugging is harder than regular JS
- No access to DOM/Window
- Work via CORS, better run from server