Web Worker Api in JavaScript
The Web Worker API in JavaScript allows you to run scripts in background threads, separate from the main execution thread of your web page. This helps keep your UI responsive while performing heavy computations or asynchronous tasks.
? What Web Workers Are For:
CPU-intensive tasks (e.g., image processing, data parsing)
Avoiding UI freeze during long operations
Offloading background logic (e.g., crypto, sorting)
?? Basic Structure
1. Create a Worker File (e.g., worker.js)
// worker.jsself.onmessage = function (e) { const result = e.data * 2; self.postMessage(result);};2. Main JS File
// main.jsconst worker = new Worker('worker.js');worker.onmessage = function (e) { console.log('Result from worker:', e.data);};worker.postMessage(5); // Sends 5 to worker.js? Communication
postMessage(data): Send data between main thread and worker.onmessage: Handle incoming messages.
? Terminate a Worker
worker.terminate();? Inline Worker (Blob URL)
If you don't want a separate file:
const code = ` self.onmessage = function(e) { self.postMessage(e.data + 1); };`;const blob = new Blob([code], { type: 'application/javascript' });const worker = new Worker(URL.createObjectURL(blob));worker.onmessage = (e) => console.log('From worker:', e.data);worker.postMessage(10);?? Limitations
No direct DOM access in the worker.
Communication is async via messages.
Workers run in isolated scope (
selfnotwindow).Same-origin policy applies.
? Tip: Use Cases
Image manipulation
Background data sync
Parsing large JSON or CSV files
Real-time calculations
Let me know if you want a demo that uses a worker for something practical like sorting a large array or image filtering!