What is Web Workers in HTML5: Explanation and Example
Web Workers allow scripts to run in the background, separate from the main browser thread. This helps keep the web page responsive by offloading heavy tasks without freezing the user interface.How It Works
Imagine your web page is like a busy kitchen where the chef (main thread) is cooking and taking orders at the same time. If the chef tries to do everything alone, the kitchen gets slow and customers wait longer. Web Workers act like assistant chefs who handle some cooking tasks separately, so the main chef can keep taking orders smoothly.
Technically, Web Workers run JavaScript code in a separate thread from the main page. This means they can perform heavy calculations or data processing without stopping the page from responding to clicks, typing, or animations. The main thread and workers communicate by sending messages back and forth.
Example
This example shows how to create a simple Web Worker that counts numbers in the background and sends updates to the main page.
// main.js const worker = new Worker('worker.js'); worker.onmessage = function(event) { document.getElementById('output').textContent = 'Count: ' + event.data; }; // Start counting worker.postMessage('start'); // worker.js self.onmessage = function(event) { if (event.data === 'start') { let count = 0; setInterval(() => { count++; self.postMessage(count); }, 1000); } };
When to Use
Use Web Workers when your web page needs to do heavy tasks like complex calculations, data processing, or fetching large files without freezing the page. For example:
- Running math or physics simulations
- Processing large data sets or images
- Handling real-time data updates
- Performing background tasks like file compression
They help keep the user interface smooth and responsive, improving user experience.
Key Points
- Runs in background: Web Workers run scripts separately from the main page.
- Non-blocking: They prevent the page from freezing during heavy tasks.
- Communication: Main thread and workers talk using messages.
- Limitations: Workers can't access the DOM directly.