What are Web Workers?
What are Web Workers?
Web Workers are a feature in HTML5 that allows JavaScript to run in the background, on a separate thread from the main execution thread of a web application. This enables the execution of computationally intensive tasks without blocking or slowing down the user interface (UI) thread, thus improving the performance and responsiveness of web applications.
Web Workers operate independently of the main thread and do not have access to the Document Object Model (DOM), meaning they cannot directly manipulate the HTML or CSS of a page. Instead, they communicate with the main thread using a system of messages. Data is sent back and forth between a Web Worker and the main thread using the postMessage
method, and messages are received with an onmessage
event handler.
There are two types of Web Workers:
Dedicated Web Workers: These are linked to the creator and can only be used by the script that spawned them. Once the parent thread is terminated, the dedicated worker is also terminated.
Shared Web Workers: These can be accessed by multiple scripts, even if they are being executed in different windows, iframes, or even different workers, as long as they are on the same domain.
Web Workers are particularly useful for tasks that require heavy computation, such as image or video processing, large data calculations, or pulling in large amounts of data from APIs without affecting the UI's performance.
To create a Web Worker, you instantiate a new Worker object and specify the path to the JavaScript file that contains the worker's code. Here's a basic example of how to create and communicate with a Web Worker:
// Main thread
var myWorker = new Worker('worker.js');
myWorker.postMessage('Hello, worker!'); // Sending a message to the worker
myWorker.onmessage = function(e) {
console.log('Message received from worker: ' + e.data);
};
// Inside worker.js
self.onmessage = function(e) {
console.log('Message received from main script: ' + e.data);
var workerResult = 'Result from worker';
self.postMessage(workerResult);
};
...
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào