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,

  1. Configure your project to use Web Workers
  2. Adds app.worker.ts to receive messages
    addEventListener('message', ({ data }) => {
    const response = `worker response to ${data}`;
  3. The component app.component.ts file updated with web worker file
    if (typeof Worker !== 'undefined') {
    // Create a new
    const worker = new Worker('./app.worker', { type: 'module' });
    worker.onmessage = ({ data }) => {
    console.log('page got message: ${data}');
    } 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.

October 14, 2022