In this article, we’ll learn how to use web workers in Angular 8/9.
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:
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') {
// Create a new
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.');
// Web Workers are not supported in this environment.
// You should add a fallback so that your program still executes correctly.
}
Step 4
Now, we can do some code in my-worker.worker.ts
addEventListener('message', ({
data
}) => {
const response = `worker response to ${data}`;
postMessage(response);
});
Step 5
Now, run the application.
npm start
Step 6
Now, we will get the following output,
Web Workers looks easy because it’s very simple and cool. After reading this, you should understand the application’s behavior.
Thank you!
#angular #angular8 #Web Workers in Angular #tutorial