Table of Contents
Are the heavy computations degrading your web app performance?
App Performance, the deciding factor in the success of a web application/website, is the major point of concern for both the developer as well as the user. Everyone desires an application that runs fast as well as is profoundly responsive.
40% of users leave the website that takes more than 3 seconds to load.- Neil Patel
Considering the fact, the developers are searching for various tools and techniques to improve the performance of the application. Web Worker (Java Script) is one such tool in this area, which brings a considerable difference in the App performance. Javascript has evolved quite a lot in the past few years, which can be gauged through the performance of the Javascript applications running over the internet and this improved performance can be ascribed to the JavaScript Engine and APIs.
However, despite the changes, the user still tends to face the problem of freezing UIs of the applications, which happens due to the heavy computations at the browser, leading to negative user experience. Web Worker proves to be the savior here, which regulates and guides the browser to process the tasks based on their sizes, i.e. larger ones in the background and the smaller ones such as basic user interactions in the front, allowing multiple threads to execute in parallel.
Doing this, Web Worker speeds up the App performance, hence, incorporating it into your app can prove to be a game-changer for your business. This article will guide you about the process of using Web Worker in your Angular Application and improve its performance.
What is a Web Worker?
Web Worker is a JavaScript code that runs in the background without interfering with other JavaScript code running within the HTML and hampering the performance of the page. The performance of an application depends highly on the thread execution and because a browser is capable of running a single thread at a time, execution time is distributed among the threads which pretend to run in parallel i.e multithreading, slowing down its performance.
Web Worker, on the other contrary, does not pretend the parallel execution, rather works actually on the concept of multithreading, which creates a Worker Thread along with the main thread (DOM thread) of the browser. The javascript code is loaded on the Worker Thread which runs in parallel in the background, however in a different environment than the DOM thread where the DOM API does not exist, thereby restricting its access to the DOM objects, such as- Windows and Document objects. Hence, the main thread can look after the UI of the website and the Web Worker will take care of the large tasks in the background.
How to use Web Worker in Angular?
Being executed in the HTML, Web Workers can be used to enhance the performance of any kind of application that runs on a browser, such as – PWA(Progressive Web Apps), SPAs, as well as websites.
Let’s consider the implementation of a Web Worker in an Angular application. The best Angular version for using Web Worker is Angular 8 onwards, which comes with an Angular CLI tool, simplifying the web pack configuration and setup of the web workers.
Why Angular Should Be Your #1 Choice to Build Applications
Why Angular NativeScript is Boon for App Development
What’s new in Angular 10?
Let’s say your Angular Application calculates the factorial of a number, which is a recursive process, hence is a time taking computation. So, check out the steps to incorporate Web Worker in your Angular application and handle the computation without affecting the other threads.
Step-1: Generate a Web Worker, using the command:
ng g web-worker web worker
The command creates a Web Worker file, named as webworker.ts, which is used by the CLI tools for further execution.
Step-2: Incorporate the application code in the Web Worker file.
Calculating the factorial of the number in the DOM thread eventually slows down the app, leading to the frozen UI until the computations are completely done.
Let’s say the code for our Angular App goes like this-
@Component({
selector: 'app',
template: `
<div>
<input type="number" [(ngModel)]="inputValue"." />
<button (click)="calcFact">Calc. Fact</button>
</div>
<div>{{output}}</div>
})
export class App {
private inputValue
private returnValue
calcFact() {
this.returnValue =factorial(this.inputValue)
}
}
function factorial(num) {
{
if(num==0)
return(1);
return(n*find_factorial(n-1));
}
}
Factorial of a small number is not a big deal, neither it will hamper the app performance, however, as soon as the number exceeds more than 10K, the difference in the speed and performance of the app can be observed due to heavy computations. Executing it in another thread can be helpful here, lifting the restriction on the number size, which can be achieved through the Web Worker by including the code along with the event listener in the webworker.ts.
function factorial(num) {
{
if(num==0)
return(1);
return(n*find_factorial(n-1));
}
}
self.addEventListener('message', (evet) => {
const num = evet.data
postMessage(factorial(num))
})
Step-3: Add the Web Worker to your application
To add the Web Worker to your application, you need to make modifications to the components of your application.
// webWorker-demo/src/app/app.component.ts
@Component({
selector: 'app',
template: `
<div>
<input type="number" [(ngModel)]="inputValue"." />
<button (click)="calcFact">Calc. Fact</button>
</div>
<div>{{returnValue}}</div> `
})
export class App implements OnInit{ // OnInit initializes the Web Worker
private inputValue //variable declaration
private returnValue
private factWorker: Worker
ngOnInit() {
if(typeof Worker !== 'undefined') {
this.factWorker = new Worker('./webWorker')
this.factWorker.onmessage = function(data) {
this.returnValue = data
}
}
}
calcFact() {
this.factWorker.postMessage(this.number)
}
}
The OnInit command initiates the Web Worker, which then invokes the event listener webworker.postMessage(… data to be executed…). The data in the postMessage() executes in the Web Worker, which is called on the completion of the task. The function calcFact() sends the number, whose factorial has to be calculated, to the web worker, which calculates the factorial in the background. The Web Worker sends the result back to the DOM thread, which is displayed by the onMessage() function.
Now the DOM just needs to look after the interaction of the user and small tasks, leaving the heavy tasks for the Web Worker, which enhances the performance of the application.
Step-4: Terminating a Web Worker
After calculating the factorial and displaying the result, the Web Worker should be terminated. There are 2 ways of terminating the Web Worker-
- terminate()– This function terminates the running Web Worker externally.
- close()- To close the Web Worker instance within itself, you can call self.close()
Wrap-up
No more struggling with the buffering and frozen UI in your app!
Web Workers, as envisioned by World Wide Web Consortium (W3C) and the Web Hypertext Application Technology Working Group (WHATWG), is a JavaScript code that facilitates multithreading and tends to use the multi-core CPUs more efficiently.
Web Worker has brought a tremendous change in the app performance as well as user interaction, allowing you to multitask without facing any degradation in the app behavior. Just add the large process to the Web Worker, and that’s it! The Worker will take care of it, allowing you to proceed with other smaller tasks.
Though Web Worker is a very helpful tool for a developer, however, tools are productive only if used deliberately, else it goes out as a wreck. If you are willing to upgrade your web app and speed up its performance through Web Worker, reach out to the experts who can utilize it strategically and bring the best out of it. Having developed and delivered numerous projects based on various powerful technologies including Web Worker, our highly skilled developer can help you through this. So, without further ado, Hire an App developer to enhance your user experience.