HTML Web Workers
Web Workers allow you to run JavaScript code in the background, on a separate thread from the main UI. This prevents heavy computations or long tasks from freezing the user interface. By posting messages between the main script and the worker, you keep the page responsive.
Key Topics
Creating a Worker
Example: var worker = new Worker('worker.js');
loads an external JS file as a worker.
Messaging Between Scripts
Use worker.postMessage()
to send data to the worker and onmessage
event in both worker and main script to handle responses.
Web Worker Example
This example shows a main script that offloads computation to a worker. A full code sample is provided below.
<!-- main.html -->
<!DOCTYPE html>
<html>
<head><meta charset="UTF-8"></head>
<body>
<button onclick="startWorker()">Start Worker</button>
<p id="result"></p>
<script>
var worker;
function startWorker() {
worker = new Worker('worker.js');
worker.onmessage = function(e) {
document.getElementById('result').textContent = 'Result: ' + e.data;
};
worker.postMessage(10); // send a number to worker
}
</script>
</body>
</html>
Explanation: The main script creates a worker and sends a message. The worker performs some computation (e.g., factorial of 10) and returns the result, which is displayed without blocking the UI.
Key Takeaways
- Web Workers run scripts in the background, off the main thread.
- Use postMessage and onmessage for communication.
- Prevent UI freezing during heavy computations.
- Workers have no DOM access, focusing on data processing.
- Ensure browser support and provide fallbacks if needed.