Web Workers API in HTML5
HTML5 includes a new API for running scripts in the background, called the Web Workers API. This API allows web developers to run JavaScript code in a separate thread, which can improve the performance of complex tasks and prevent the user interface from freezing. Here's an example of how to use the Web Workers API to perform a time-consuming calculation:
php
<!DOCTYPE html>
<html>
<head>
<title>My Web Page</title>
<script>
var worker = new Worker("worker.js");
worker.onmessage = function(event) {
document.getElementById("result").innerHTML = event.data;
};
function calculate() {
var number = document.getElementById("number").value;
worker.postMessage(number);
}
</script>
</head>
<body>
<label for="number">Enter a number:</label>
<input type="number" id="number">
<button onclick="calculate()">Calculate</button>
<p id="result"></p>
</body>
</html>
In this example, we use the Web Workers API to perform a time-consuming calculation, using a separate JavaScript file called "worker.js". When the user enters a number and clicks the "Calculate" button, we use the postMessage() method to send the number to the worker. The worker then performs the calculation in the background and sends the result back to the main thread using the onmessage event handler.
No comments:
Post a Comment