Web Workers are a feature of the HTML5 standard that allows you to run scripts in the background, independent of other scripts that may be running in the main page. They enable parallel processing in JavaScript, which is otherwise single - threaded.
window
. Instead, they use the self
object to refer to their global scope.worker.js
) that will contain the code to be run in the worker.// worker.js
self.onmessage = function(event) {
// Receive data from the main script
const data = event.data;
// Do some heavy - lifting task
let result = 0;
for (let i = 0; i < data; i++) {
result += i;
}
// Send the result back to the main script
self.postMessage(result);
};
Worker
object and communicate with it.<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF - 8">
</head>
<body>
<script>
// Create a new worker
const worker = new Worker('worker.js');
// Send data to the worker
worker.postMessage(1000000);
// Receive data from the worker
worker.onmessage = function(event) {
const result = event.data;
console.log('Result from worker:', result);
};
// Handle errors
worker.onerror = function(error) {
console.error('Worker error:', error.message);
};
</script>
</body>
</html>
To stop a worker from running, you can call the terminate()
method on the worker object in the main script.
worker.terminate();
postMessage()
: The postMessage()
method is used to send data between the main script and the worker. It can send various types of data, including strings, numbers, arrays, and objects.// Main script
worker.postMessage({ name: 'John', age: 30 });
// Worker script
self.onmessage = function(event) {
const data = event.data;
console.log('Received data:', data);
};
onerror
Event: In both the main script and the worker, you can listen for the onerror
event to handle errors that occur during the execution of the worker.// Main script
worker.onerror = function(error) {
console.error('Worker error:', error.message);
};
// Worker script
self.onerror = function(error) {
console.error('Error in worker:', error.message);
};
ArrayBuffer
) to transfer data without copying it, which can significantly improve performance.// Main script
const buffer = new ArrayBuffer(1024);
worker.postMessage(buffer, [buffer]);
// Worker script
self.onmessage = function(event) {
const buffer = event.data;
// The buffer is now owned by the worker
};
Web Workers are a powerful feature in JavaScript that can greatly enhance the performance and responsiveness of web applications. By allowing parallel processing, they enable developers to offload heavy - lifting tasks from the main thread, ensuring that the user interface remains smooth and responsive. Understanding the fundamental concepts, usage methods, common practices, and best practices of Web Workers is essential for building high - performance web applications.