Skip to main content
InterviewHubPRO
Section Overview
Q118

Question 118 of 283

Part 5: Animations, Service Workers, Ivy Engine & Builders (101 - 123)

42%
Angular Master (283 Qs)•Part 5: Animations, Service Workers, Ivy Engine & Builders (101 - 123)

How do you add web workers in your application?

mid LevelCode ExampleangularAnimations

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,

  1. Configure your project to use Web Workers
  2. Adds app.worker.ts to receive messages
javascript
   addEventListener('message', ({ data }) => {
     const response = `worker response to ${data}`;
     postMessage(response);
   });
  1. The component app.component.ts file 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.