Câu hỏi phỏng vấn HTML
Câu hỏi

What are Web Workers?

Câu trả lời

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:

  1. 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.

  2. 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

middle

Gợi ý câu hỏi phỏng vấn

junior

How Can I Get Indexed Better by Search Engines?

middle

When is it appropriate to use the small element?

middle

Where and why is the rel="noopener" attribute used?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào