Middle
What are web workers and what are they used for?
sobes.tech AI
Answer from AI
Web workers are a way to run JavaScript code in a background thread separate from the main UI thread of the browser.
Purpose:
- Performing resource-intensive computations without blocking the main thread, preventing interface freezing.
- Processing large data or performing long operations (e.g., parsing, compression, network requests in some cases) in the background.
- Improving the performance and responsiveness of web applications.
Types of web workers:
- Dedicated Worker: Associated with the script that created it.
- Shared Worker: Can be shared among multiple scripts running in different windows or tabs of the same domain.
- Service Worker: Intercepts network requests, manages caching, provides offline access, and supports push notifications.
Example of creating and using a Dedicated Worker:
// main.js (main thread)
const worker = new Worker('worker.js');
// Sending a message to the worker
worker.postMessage('Start heavy computations');
// Receiving a message from the worker
worker.onmessage = function(event) {
console.log('Received from worker:', event.data);
};
// worker.js (worker code)
self.onmessage = function(event) {
console.log('Received in worker:', event.data);
// Simulating heavy computations
let result = 0;
for (let i = 0; i < 1000000000; i++) {
result += i;
}
// Sending message back to main thread
self.postMessage('Calculations completed, result: ' + result);
};
Limitations:
- No direct access to DOM.
- Cannot use some global variables of the main thread (e.g.,
window,document). - Communication occurs via asynchronous message exchange (
postMessageandonmessage/addEventListener('message')). - Data between threads is transferred via copying (structured clone algorithm), but for large data,
Transferable Objectscan be used for transfer by reference (losing access in the original thread).