Middle
What are Web Workers and what are they used for?
sobes.tech AI
Answer from AI
Web Workers allow scripts to run in the background thread, without blocking the main browser thread (UI thread).
They are useful for performing resource-intensive tasks such as:
- Processing large amounts of data.
- Calculations.
- Loading and parsing files.
- Working with graphics.
Using Web Workers helps avoid "freezing" the user interface during long operations, maintaining application responsiveness.
Main characteristics:
- No access to DOM: Cannot directly manipulate page elements.
- Communication via messages: Exchange data with the main thread using
postMessage()andonmessageevent handler. - Limited access to browser API: No access to
window,document,parent. Available arenavigator,location(read-only), and some other APIs. - Separate scope: Each worker has its own global object
self.
Example of creation and usage:
In the main script:
// Creating a Web Worker instance
const myWorker = new Worker('worker.js');
// Sending a message to the worker
myWorker.postMessage('Hello from the main thread!');
// Handling messages from the worker
myWorker.onmessage = function(event) {
console.log('Message received from worker:', event.data);
};
// Handling worker errors
myWorker.onerror = function(error) {
console.error('Worker error:', error.message);
};
// Terminating the worker
// myWorker.terminate();
In the worker.js file (worker script):
// Handling messages from the main thread
onmessage = function(event) {
console.log('Message received from main thread:', event.data);
// Performing some task
const result = 'Calculation result';
// Sending message back to main thread
postMessage(result);
};
There are different types of workers:
Dedicated Workers: Bound to a specific tab or window.Shared Workers: Can be used by multiple scripts from different windows or tabs of the same domain.Service Workers: Proxy server that operates between the browser and the network, used for caching and offline work.
Comparison table of Dedicated and Shared Workers:
| Characteristic | Dedicated Worker | Shared Worker |
|---|---|---|
| Scope | Single script/window | Multiple scripts/windows |
| Communication | Direct postMessage |
Via Port |
| Creation | new Worker(url) |
new SharedWorker(url) |
| Termination | worker.terminate() |
Automatically when no active ports |