Angular & Signals (283 Qs)•Part 5: Animations, Service Workers, Ivy Engine & Builders (101 - 123)
How do you add web workers in your application?
You can add web worker anywhere in your application. For example, If the file that contains your expensive computation is src/app/app.component.ts, you can add a Web Worker using ng generate web-worker app command which will create src/app/app.worker.ts web worker file. This command will perform below actions,
- Configure your project to use Web Workers
- Adds app.worker.ts to receive messages
javascript
addEventListener('message', ({ data }) => {
const response = `worker response to ${data}`;
postMessage(response);
});
- The component
app.component.tsfile updated with web worker file
javascript
if (typeof Worker !== 'undefined') {
// Create a new
const worker = new Worker('./app.worker', { type: 'module' });
worker.onmessage = ({ data }) => {
console.log('page got message: $\{data\}');
};
worker.postMessage('hello');
} else {
// Web Workers are not supported in this environment.
}
Note: You may need to refactor your initial scaffolding web worker code for sending messages to and from.