Overview

A web worker is a JavaScript script running in the background, without affecting the performance of the page.

Browser Support

This browser does not support Web Workers.


1. Create a worker

In the terminal (from your workspace folder) run the following CLI command to create a worker in your Angular project

ng g web-worker app

The worker looks like this:

/// <reference lib="webworker" />

addEventListener('message', ({ data }) => {
    const response = `worker response to ${data}`;
    postMessage(response);
});

This code will be add to your app.component.ts

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.
    // You should add a fallback so that your program still executes correctly.
}