Web Workers in Angular

Gurseerat Kaur
CodeX
Published in
2 min readAug 7, 2022

--

Understand how to use web workers in Angular for background processing

In this article, I’ll explain what are web workers, where you can use them, and how to use them in Angular specifically. If you have a general idea on how to build them in Javascript, that’s amazing. If not, I’ve got you covered 😎

Let’s start!

What are Web Workers?

Web workers are used for running any script in the background threads, without interfering with the user’s interface. So if you have heavy computations on your user side, you can use web workers to do the heavy tasks while allowing the browser to give your users a smooth and better experience.

In Angular context, this does not mean that CLI supports running Angular in web worker.

Creating a Web Worker

It’s quite easy to create a web worker in Angular. You can use Angular CLI and use ng generate command.

ng generate web-worker <location>

This command will do the following:

  1. Creates a new file tsconfig.worker.json. This file looks as below.

2. Creates app.worker.ts and this is where you get the response from the worker.

3. In angular.json, adds ”webWorkerTsConfig”: “tsconfig.worker.json” in build > options and registers the generated tsconfig file for the web worker.

4. Your app.component.ts will also be modified and the worker will be used here.

Now if you run your Angular application using npm start, you can see the above response in Console.

Example

Let’s create a small application where we’ll use the web worker. I’ve created a small application that calculates factorial using web worker.

In the above code, you can see that we are sending data to the web worker using worker.postMessage(factorialInput) and we’re receiving the response from the worker in worker.onmessage property.

Thus, you can use web workers in your project and optimize your application. For other ways you can optimize your angular application, give a read to Reduce Initial Load Time of Angular Application.

Happy Coding 😋

--

--

Gurseerat Kaur
CodeX
Writer for

Front End Developer | Part time coder, part time learner | Chicken Biryani fan