Introduction
In this article, we'll learn how to use web workers in Angular 8/9.
Web Workers
Web workers speed up in your application when we start working on CPU-intensive tasks. They let you offload work to a background thread. Once we allow a web worker to run, we can use it normally in our application, and the Angular cli will be able to split bundle and code.
The Following Browser versions which are supported in web workers:
- Firefox: 3.5
- Chrome: 4
- Safari: 4
- IE:10
- Opera: 10.6
Installing AngularCLI
Let’s get started by installing Angular CLI, which is the official tool for creating and working with Angular projects. Open a new terminal and run the below command to install Angular CLI.
npm install -g @angular/cli.
If you want to install Angular 9, simply add @next
npm install --g @angular/cli@next
Please check the below command for the Angular version.
ng version
Steps to follow:
Step 1
Create an Angular project setup using the below command or however you want to create it.
ng new projectname
Example,
ng new webworker
Step 2
Now, we must generate web workers from our Angular cli. Open a new terminal and run the below command.
ng generate webWorker my-worker
Step 3
Now, Create a Web Worker Object in App.component.ts(main scripts)
- const worker = new Worker ('./my-worker.worker', {type: 'module'});
We can do some code in App.component.ts (main scripts)
- if (typeof Worker !== 'undefined') {
-
- const worker = new Worker('./my-worker.worker', {
- type: 'module'
- });
- worker.onmessage = ({
- data
- }) => {
- console.log(`page got message: ${data}`);
- };
- worker.postMessage('welcome');
- } else {
- console.log('Web Workers are not supported in this environment.');
-
-
- }
Step 4
Now, we can do some code in my-worker.worker.ts
- addEventListener('message', ({
- data
- }) => {
- const response = `worker response to ${data}`;
- postMessage(response);
- });
- Web Workers are supported in the browser
- Create a new worker (main scripts).
- Post message to the worker in my-worker.worker.ts.
- When the worker gets the message, addEventListener will fire, and it will create a response to the object then it will call postMessage method.
Step 5
Now, run the application.
npm start
Step 6
Now, we will get the following output,
Conclusion
Web Workers looks easy because it's very simple and cool. After reading this, you should understand the application's behavior.