202 lines
7.8 KiB
Plaintext
202 lines
7.8 KiB
Plaintext
---
|
||
title: What are workers in javascript used for?
|
||
---
|
||
|
||
## TL;DR
|
||
|
||
Workers in JavaScript are background threads that allow you to run scripts in parallel with the main execution thread, without blocking or interfering with the user interface.
|
||
|
||
### Key features
|
||
|
||
- **Parallel Processing** : Workers run in a separate thread from the main thread, allowing your web page to remain responsive to user interactions while the worker performs its tasks.
|
||
- **Communication** : Uses `postMessage` and `onmessage` for messaging.
|
||
- **Access to Web APIs**: Workers have access to various Web APIs, including `Fetch` API, `IndexedDB`, and `LocalStorage`, allowing them to perform tasks like data fetching and persisting data independently.
|
||
- **No DOM Access** : Workers cannot directly manipulate the `DOM` or interact with the `UI`, ensuring they don't accidentally interfere with the main thread's operation.
|
||
|
||
There are two main types of workers:
|
||
|
||
### Web workers
|
||
|
||
- Run scripts in background threads, separate from the main `UI` thread.
|
||
- Useful for CPU-intensive tasks like data processing, calculations, etc.
|
||
- Cannot directly access or manipulate the `DOM`.
|
||
|
||
### Service Workers:
|
||
|
||
- Act as network proxies, handling requests between the app and network.
|
||
- Enable offline functionality, caching, and push notifications.
|
||
- Run independently of the web app, even when it's closed.
|
||
|
||
---
|
||
|
||
## Workers in JavaScript
|
||
|
||
Workers in JavaScript are a way to run scripts in background threads, separate from the main execution thread of a web page. This allows for long-running or computationally intensive tasks to be offloaded from the main thread, preventing the user interface from becoming unresponsive or janky.
|
||
|
||
## Types of Workers
|
||
|
||
#### Web Workers
|
||
|
||
- Run scripts in background threads separate from the main `UI` thread
|
||
- Designed for CPU-intensive tasks like data processing, computations, etc.
|
||
- Cannot directly access the `DOM` or other main thread resources for security
|
||
- Communicate with main thread via asynchronous message passing
|
||
- Terminated when main script is unloaded or explicitly terminated
|
||
|
||
#### Use cases for web worker :
|
||
|
||
- Image/video processing
|
||
- Data compression
|
||
- Complex math
|
||
|
||
#### Creating a Web Worker
|
||
|
||
To create a web worker, you need a separate JavaScript file that contains the code for the worker. Here’s an example:
|
||
|
||
**main.js (main script)**
|
||
|
||
```js
|
||
// Check if the browser supports workers
|
||
if (window.Worker) {
|
||
// Create a new Worker
|
||
const myWorker = new Worker('worker.js');
|
||
|
||
// Post a message to the worker
|
||
myWorker.postMessage('Hello, Worker!');
|
||
|
||
// Listen for messages from the worker
|
||
myWorker.onmessage = function (event) {
|
||
console.log('Message from Worker:', event.data);
|
||
};
|
||
|
||
// Error handling
|
||
myWorker.onerror = function (error) {
|
||
console.error('Error from Worker:', error);
|
||
};
|
||
}
|
||
```
|
||
|
||
**worker.js (worker script)**
|
||
|
||
```js
|
||
// Listen for messages from the main script
|
||
onmessage = function (event) {
|
||
console.log('Message from Main Script:', event.data);
|
||
|
||
// Perform a task (e.g., some computation)
|
||
const result = event.data + ' - Processed by Worker';
|
||
|
||
// Post the result back to the main script
|
||
postMessage(result);
|
||
};
|
||
```
|
||
|
||
In this example:
|
||
|
||
- `main.js` creates a worker using the `Worker` constructor and specifies `worker.j`s as the script to run in the worker thread.
|
||
- It posts a message to the worker using `postMessage`.
|
||
- The worker script (`worker.js`) listens for messages from the main script using `onmessage`.
|
||
- After processing the message, the worker posts a message back to the main script using `postMessage`.
|
||
- The main script listens for messages from the worker using `onmessage` on the `Worker` instance.
|
||
|
||
### Service Workers
|
||
|
||
- Act as a network proxy between web app, browser, and network
|
||
- Can intercept and handle network requests, cache resources
|
||
- Enable offline functionality and push notifications
|
||
- Have a lifecycle managed by the browser (install, activate, update)
|
||
- Limited access to `DOM` and main thread resources for security
|
||
|
||
#### Use cases for service workers:
|
||
|
||
- Caching
|
||
- Offline support
|
||
- Request handling
|
||
- Background sync
|
||
|
||
#### Creating a service Worker
|
||
|
||
**In main.js (main script)**
|
||
|
||
```js
|
||
if ('serviceWorker' in navigator) {
|
||
navigator.serviceWorker
|
||
.register('/service-worker.js')
|
||
.then(function (registration) {
|
||
console.log('Service Worker registered:', registration);
|
||
})
|
||
.catch(function (err) {
|
||
console.log('Service Worker registration failed:', err);
|
||
});
|
||
}
|
||
```
|
||
|
||
**service-worker.js (service worker script)**
|
||
|
||
```js
|
||
self.addEventListener('fetch', function (event) {
|
||
event.respondWith(
|
||
caches.match(event.request).then(function (response) {
|
||
// return cached response if available
|
||
if (response) {
|
||
return response;
|
||
}
|
||
|
||
// Otherwise, fetch from network
|
||
return fetch(event.request);
|
||
}),
|
||
);
|
||
});
|
||
```
|
||
|
||
In this example:
|
||
|
||
- The main script registers a `Service worker` at `/service-worker.js`.
|
||
- The Service worker listens for the `fetch` event, which is fired whenever the browser makes a network request.
|
||
- The Service worker first checks if the requested resource is cached using `caches.match(event.request)`.
|
||
- If it is, it returns the cached response. Otherwise, it fetches the resource from the network using `fetch(event.request)`.
|
||
|
||
### Shared Workers
|
||
|
||
- Can be accessed from multiple scripts in different windows/tabs/iframes
|
||
- Allow data sharing between browser contexts via a messaging interface
|
||
- Similar to dedicated Web Workers but with a broader scope
|
||
|
||
### Use cases for service workers:
|
||
|
||
- State sharing across multiple windows
|
||
|
||
### Worklets
|
||
|
||
- Lightweight workers for specific use cases like painting, audio processing
|
||
- Run in separate threads from main UI thread
|
||
- Provide a way to extend browser rendering engines with custom logic
|
||
- **Types**: Animation Worklets, Audio Worklets, Layout Worklets, Paint Worklets
|
||
|
||
### Use cases for worklet:
|
||
|
||
- Custom CSS animations
|
||
- Audio effects
|
||
- Layout calculations
|
||
|
||
The key differences lie in their intended purposes, scope, and access to browser APIs. Web Workers are for CPU-intensive tasks, Service Workers handle network requests and offline, Shared Workers enable cross-window communication, and Worklets extend browser rendering capabilities.
|
||
|
||
## Considerations and Limitations
|
||
|
||
- **Same-Origin Policy**: Workers must comply with the same-origin policy, meaning the script that creates the worker and the worker script itself must be from the same origin.
|
||
- **No DOM Access**: Workers do not have direct access to the DOM. They can communicate with the main thread through messages.
|
||
- **Performance**: Creating and managing workers incurs overhead. They should be used judiciously for tasks that truly benefit from parallel execution.
|
||
- **Error Handling**: Proper error handling mechanisms should be in place to handle any issues within the worker scripts.
|
||
|
||
## Conclusion
|
||
|
||
Workers in JavaScript are a powerful tool for improving the performance and responsiveness of web applications by offloading time-consuming tasks to background threads. They enable more efficient and smoother user experiences, especially for applications requiring heavy computations or asynchronous processing. By understanding and utilizing workers effectively, developers can create more robust and high-performing web applications.
|
||
|
||
## Further reading
|
||
|
||
- [Worker - MDN](https://developer.mozilla.org/en-US/docs/Web/API/Worker)
|
||
- [Using Web Workers - MDN](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers)
|
||
- [Service Worker API - MDN](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API)
|
||
- [Understanding web workers in JavaScript with real world example ](https://javascript.plainenglish.io/understanding-web-workers-in-js-with-real-world-example-1629a283aeec?gi=89cf0dd4c3f4)
|
||
- [Web worker, Service worker, and Worklets: A comprehensive guide](https://dev.to/bharat5604/web-worker-service-worker-and-worklets-a-comprehensive-guide-1f64)
|