Web Workers in HTML
? Web Workers in HTML (HTML5)
Web Workers in HTML5 allow you to run JavaScript scripts in the background, separate from the main UI thread. This helps improve performance and prevents the UI from freezing or becoming unresponsive during intensive tasks.
? What Is a Web Worker?
A Web Worker is a JavaScript file that runs in a separate background thread. It can:
Perform heavy computations (e.g., data processing, fetching large data)
Send messages to/from the main script via events
Not access the DOM directly
? Basic Syntax
1. Create a Worker File (worker.js):
// worker.jsonmessage = function(e) { const result = e.data * 2; postMessage(result);};2. Main HTML/JS File:
<!DOCTYPE html><html><body> <h2>Web Worker Example</h2> <button onclick="startWorker()">Start Worker</button> <p id="result"></p> <script> let worker; function startWorker() { if (typeof(Worker) !== "undefined") { if (!worker) { worker = new Worker("worker.js"); } worker.onmessage = function(e) { document.getElementById("result").innerText = "Result: " + e.data; }; worker.postMessage(10); // Send data to worker } else { alert("Web Workers are not supported in your browser."); } } </script></body></html>? Worker Limitations
| Feature | Support |
|---|---|
| Access to DOM | ? No |
Access to window | ? No |
Access to navigator | ? Partial |
| File I/O | ? No |
| XMLHttpRequest/Fetch | ? Yes |
? Terminating a Worker
worker.terminate(); // Stops the worker? Real-World Use Cases
Background calculations (e.g., image manipulation)
Fetching large datasets
Real-time analytics
Offloading cryptographic operations
? Summary
| Feature | Benefit |
|---|---|
| Multithreading | Keeps UI responsive during heavy tasks |
| Async Messaging | Uses postMessage() and onmessage |
| Easy to use | Just create a .js file and call it |
Would you like a complete example project like a live character counter or image processor using Web Workers?