Web Workers enable running scripts in the background independently of the main UI thread. This allows complex computations to be performed without blocking the user interface. Some facts are as follows:
- DOM manipulation is not allowed inside worker file and cannot use window object properties or methods.
- Communication between main thread and worker happens using postMessage() and response to message via onmessage event handler.
- Dedicated worker uses single script file
- Shared worker uses multiple script files.
Here’s an example of implementing a Web Worker in a simple HTML project.
Step 1: Create the HTML Document
Create an HTML file with two buttons (Calculate and Welcome) and two <div> elements for displaying output. The HTML structure is as follows:
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Workers</title>
</head>
<body>
<div>
<h1>All About JS Workers</h1>
</div>
<button id="btn1">Calculate</button>
<button id="btn2">Welcome</button>
<br /><br />
<div id="value1"></div>
<div id="value2"></div>
<script src="complex.js"></script>
<script>
let counter = 0;
const btnWelcome = document.getElementById("btn2");
// Handle "Welcome" button click
btnWelcome.addEventListener("click", () => {
counter++;
document.getElementById("value2").innerHTML = `Welcome... ${counter}`;
});
</script>
</body>
</html>
Step 2: Create the External JavaScript File (complex.js)
The complex.js file contains the logic to create a Web Worker and communicate with it. This script handles the Calculate button click and executes complex computations using a background worker (worker.js).
const btn = document.getElementById("btn1");
btn.addEventListener("click", () => {
// Check if the browser supports Web Workers
if (window.Worker) {
const wrkObj = new Worker("worker.js");
// Send a message to the worker
wrkObj.postMessage("Start worker...");
// Receive data from the worker
wrkObj.onmessage = function (e) {
console.log("Received data:", e.data);
document.getElementById("value1").innerHTML = `<h1>${e.data}</h1>`;
};
}
});
Explanation
- Creating the Worker: The Worker object is instantiated with the reference to worker.js.
- Communication:
- The postMessage() method sends data to the worker.
- The worker responds using the onmessage event handler.
- Browser Support: The script checks for window.Worker to ensure Web Worker support.
Step 3: Create the Worker Script (worker.js)
The worker.js file performs a computationally intensive task in the background. This script communicates with the main thread via postMessage() and onmessage.
// DOM manipulation is not allowed in the worker
// Communication happens via postMessage and onmessage
onmessage = function (e) {
let sum = 0;
// Perform a complex operation (e.g., calculating a large sum)
for (let i = 0; i < 9999999999; i++) {
sum += i;
}
console.log(sum);
// Send the result back to the main thread
postMessage(sum);
};
Key Points
- Background Execution: The worker runs independently of the main UI thread.
- No DOM Manipulation: Workers cannot access the DOM or window object.
- Single Script: A dedicated worker is associated with a single script file.
- Communication: Messages are exchanged between the main thread and worker using postMessage() and onmessage.
Summary
- HTML Document: Contains UI elements and inline script for basic functionality.
- complex.js: Handles Web Worker creation and communication.
- worker.js: Performs the background task and sends the result to the main thread.
This example demonstrates how Web Workers can offload intensive tasks, keeping the UI responsive. Use Web Workers whenever you need to perform CPU-intensive tasks in your JavaScript applications.
No comments:
Post a Comment