How to Use Web Workers in JavaScript for Background Tasks
Use
Web Worker by creating a new Worker object with a JavaScript file URL. Communicate with the worker using postMessage and listen for messages with onmessage to run code in the background without blocking the main thread.Syntax
To use a web worker, create a new Worker by passing the path to a JavaScript file. Use postMessage to send data to the worker and listen to onmessage events to receive data back.
new Worker('worker.js'): creates a worker from a separate file.worker.postMessage(data): sends data to the worker.worker.onmessage = (event) => {}: receives messages from the worker.
javascript
const worker = new Worker('worker.js'); worker.postMessage('Hello Worker'); worker.onmessage = (event) => { console.log('Message from worker:', event.data); };
Example
This example shows how to create a web worker that calculates the sum of numbers in the background and sends the result back to the main script.
javascript
// main.js const worker = new Worker('worker.js'); worker.postMessage([1, 2, 3, 4, 5]); worker.onmessage = (event) => { console.log('Sum from worker:', event.data); }; // worker.js self.onmessage = (event) => { const numbers = event.data; const sum = numbers.reduce((a, b) => a + b, 0); self.postMessage(sum); };
Output
Sum from worker: 15
Common Pitfalls
Common mistakes when using web workers include:
- Trying to access DOM elements inside the worker (not allowed).
- Not providing the correct path to the worker script.
- Forgetting to handle messages properly with
onmessage. - Not terminating workers when done, which can waste resources.
Always remember workers run in a separate thread and have no access to the main page's variables or DOM.
javascript
// Wrong: Accessing DOM inside worker (worker.js) // document.getElementById('output').textContent = 'Hello'; // This will cause an error // Right: Send data back to main thread and update DOM there self.postMessage('Hello from worker'); // In main.js worker.onmessage = (event) => { document.getElementById('output').textContent = event.data; };
Quick Reference
| Feature | Description |
|---|---|
| new Worker('file.js') | Creates a new web worker from a JavaScript file |
| worker.postMessage(data) | Sends data to the worker thread |
| worker.onmessage = (e) => {} | Receives messages from the worker |
| self.postMessage(data) | Sends data from worker back to main thread |
| worker.terminate() | Stops the worker to free resources |
Key Takeaways
Create a web worker with new Worker('file.js') to run code in the background.
Use postMessage and onmessage to communicate between main script and worker.
Workers cannot access the DOM or main thread variables directly.
Always terminate workers when they are no longer needed to save resources.
Web workers improve performance by offloading heavy tasks from the main thread.