What is Web Worker ?
To solve this critical issue Web Worker came into picture.
Web Worker is an asynchronous system for web pages that allows execution of task in the background, independently from main thread and website UI.
Let’s see the issue
Web Worker will be used to fix this issue. Let’s see how ?
Following is the content of bigLoop.js file. This makes use of postMessage() API to pass the communication back to main page (above page):
If you run the above code then you will notice that this time your web page will not hang even this big loop will also run. This is because using Web Worker which runs this big loop in the background thread and will not impact the main UI thread.
Web Worker integration with Angular
To generate a Web Worker, we run the
ng g web-worker command:
ng generate web-worker app
This will generate
app.worker.ts file in the
src/app of an Angular app. The
web-worker tells the CLI tools that the file would be used by a Worker.
app.worker.ts file content
In the above file you will put the code which is quite CPU intensive like the big loop logic highlighted in the above example. And this code will be executed in the separate background thread since its part of Web Worker.
Also if you open app.component.ts file then you will see below lines added:
from the above code you will pass necessary info to the Web Worker file (app.worker.ts) using postMessage API and receive the processed data from the Web Worker file using worker.onmessage event.
You can now create your own worker files as well if need but remember all worker file names should be suffixed with .worker.ts
Using Web Worker
Workers don’t have access to the DOM APIs. They can’t access any of the following:
Web Workers can access:
Web Workers can also access
I hope this article will help you to further improve your angular web pages.