How to Improve the Performance of your Angular App

When it comes to web app framework, AngularJS is the highest used technology today. It is considered the best technology and structural framework to develop dynamic web applications. The modular approach to web design and massive community support make the framework extremely popular among developers across the globe. But, the Angular app performance can be even optimized further by adopting some expertly suggested tips and tricks.

Projects developed on Angular perform well on the track and expectations of vendors and developers. There are some of the top and high traffic websites such as Google, Virgin America and many others which are performing well. So, if you have a project and want to develop on Angular, then adopting the new Angular tips will help you boost the performance of your applications.

In short, the popularity of Angular is continuously growing after the arrival of Angular 8. Even though the Angular has plenty of its own optimization, experts struggle to get smooth hands and performance of the framework. In some cases, the wrong use Angular can also lead to the bad performance of the applications. Therefore, we shall be discussing every aspect of Angular and how you can improve the Angular app performance.

When you want the app, developed on Angular, perform in terms of user experience and speed and performance, there are two things which you need to be more focused upon;

  • Load Time Performance
  • Run Time Performance

Focusing on these aspects will help you optimize your angular app performance.

Let’s learn how to;

Load Time Performance

To optimize load time performance, there are some of the essential tools, tips and tricks which can help you boost your app performance. Let’s take a look at some of the expertly suggested tips;

AOT

The Angular Components and HTML Templates are hard to understand by browsers directly unless the Angular HTML and TypeScript code is converted into efficient JavaScript code. That process is done by compilers like JIT and AOT, provided by Angular.

  • JIT stands for Just-in-Time, and it compiles the app in the browser
  • AOT stands for Ahead-of-Time (AOT) and organizes the app at build time

You need to use command such as aot options with ng build or ng server.

Here’s how;

ng build --aot
ng serve --aot

How it works;

AOT will extract metadata which will work to interpret with the part of the application which will be manged by the Angular. Using commands like @Component() and @Input(), things can be specified.

Check out the example;


@Component({

selector: 'app-typical',

template: '<div>A typical component for {{data.name}}</div>'

)}

export class TypicalComponent {

@Input() data: TypicalData;

constructor(private someService: SomeService) { ... }

}

Tree-Shaking

When you want your Angular App to perform well, Tree-Shaking is essential here to help developers to write clean code. Tree shakable will enabled by default when you use Angular 6 or upper version. You just have to run your build into prod.

Here’s the example;


ng build --prod or ng serve --prod

Now, all unwanted code will be removed by the ‘tree-shaking feature.

 

 

Folder Structure for Angular

Creating a folder structure is an extremely important factor that you should consider before initiating your project. If you have not structured the folder properly, you have invited plenty of problems which keep haunting you throughout your development process. Whether it medium and large-sized project, you will come across plenty of changes in the middle of development and your project should easily adapt the new changes made in the middle of development. And, that is possible when you have created a proper folder in place.

Here’s the folder structure here;


|-- app
     |-- modules
       |-- home
           |-- [+] components
           |-- [+] pages
           |-- home-routing.module.ts
           |-- home.module.ts
     |-- core
       |-- [+] authentication
       |-- [+] footer
       |-- [+] guards
       |-- [+] http
       |-- [+] interceptors
       |-- [+] mocks
       |-- [+] services
       |-- [+] header
       |-- core.module.ts
       |-- ensureModuleLoadedOnceGuard.ts
       |-- logger.service.ts
     |
     |-- shared
          |-- [+] components
          |-- [+] directives
          |-- [+] pipes
          |-- [+] models
     |
     |-- [+] configs
|-- assets
     |-- scss
          |-- [+] partials
          |-- _base.scss
          |-- styles.scss

All your source code can be stored in the structured folder here.

Uglify

This is a very important feature which helps developers reduce the size of applications. Developers can do this by adopting various code transformations. You need to use the webpack to install the uglifyjs-webpack-plugin.


$ npm install uglifyjs-webpack-plugin --save-dev

For configuration you need to use the following command;


const UglifyJsPlugin = require('uglifyjs-webpack-plugin');

module.exports = {

optimization: {

minimizer: [new UglifyJsPlugin()],

},

};

Now, you will get the app size reduced significantly. Uglify which is a JavaScript parser minifier, compressor and beautifier toolkit and will help reduce the app size to the minimalist.

Build-optimizer flag

Specifying “build-optimizer” flag when you use ‘angular-cli If you are using angular-cli for your production build. It will help create smaller code by disabling the vendor chunk. When you have shorter code, the size of the app automatically reduced to the minimalist, and it will result in smooth performance, speed and enhanced user-experience.

Server-side rendering

Rendering the first page of your application on the server can boost performance, speed and load time. You need to use Node.js, .Net, PHP to comply with the purpose. At the same time, the normal does have such facility as you have to use Angular Universal to perform server-side rendering.

How to create a server-side module?

Use a command like;



-- ng add @nguniversal/express-engine 
-- clientProject angular.io-example

You will find the following folder structure;


src/

index.html                  app web page

main.ts                     bootstrapper for client app

main.server.ts              bootstrapper for server app

style.css                   styles for the app

app/ ...                    application code

app.server.module.ts        server-side application module

server.ts                   express web server

tsconfig.json               TypeScript client configuration

tsconfig.app.json           TypeScript client configuration

tsconfig.server.json        TypeScript server configuration

tsconfig.spec.json          TypeScript spec configuration

package.json                npm configuration

webpack.server.config.js    webpack server configuration

To Begin Rendering Use the Following Command;


npm run build:ssr && npm run serve:ssr

Benefits of Server-Side Rendering

  • Helping Web Crawlers find the page easily
  • Easy use on mobile and low powered devices
  • Easy loading and quick appearance of the first page on any device

 

 

Lazy Loading Feature Module

Utilizing LazyLoad the modules can enhance your productivity. Lazy Load is a built-in feature in Angular which helps developers with loading the thing which is required. For example, when you use the feature, it loads the components and other things you needed and stops other and unnecessary files from getting loaded.

Here’s how it functions;


// app.routing.ts

{ path: 'not-lazy-loaded', component: NotLazyLoadedComponent }

Here the ‘LazyLoading‘ is not in place, and you will end creating large and unnecessarily heavy-sized applications.

When you use;


// app.routing.ts
{
path: 'lazy-load',
loadChildren: 'lazy-load.module#LazyLoadModule'
}
// lazy-load.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
import { LazyLoadComponent }  from './lazy-load.component';
@NgModule({
imports: [
CommonModule,
RouterModule.forChild([
{
path: '',
component: LazyLoadComponent
}
])
],
declarations: [
LazyLoadComponent
]
})
export class LazyModule {}

You have used ‘LazyLoad‘, and it helps you reduce the size of the application by keeping abstaining from unnecessary file from loading.

RxJS 6

RxJS 6 yet another library which make things more tree-shakable that result in reducing the final bundle size. It is used for reactive programming using observables which makes callback-based code easier.

How to Create RxJS

You have plenty of functions to create observables such as;

  • Events
  • Promise
  • Counter
  • AJAX request

Creation Observables from Event


import { fromEvent } from 'rxjs';

const el = document.getElementById('my-element');

// Create an Observable that will publish mouse movements

const mouseMoves = fromEvent(el, 'mousemove');

// Subscribe to start listening for mouse-move events

const subscription = mouseMoves.subscribe((evt: MouseEvent) => {

// Log coords of mouse movements

console.log(`Coords: ${evt.clientX} X ${evt.clientY}`);

// When the mouse is over the upper-left of the screen,

// unsubscribe to stop listening for mouse movements

if (evt.clientX < 40 && evt.clientY < 40) {

subscription.unsubscribe();
}
});

Creation Observables from Promise


import { from } from 'rxjs';

// Create an Observable out of a promise

const data = from(fetch('/api/endpoint'));

// Subscribe to begin listening for async result

data.subscribe({

next(response) { console.log(response); },

error(err) { console.error('Error: ' + err); },

complete() { console.log('Completed'); }

});

Creation Observables from Counter


import { interval } from 'rxjs';

// Create an Observable that will publish a value on an interval

const secondsCounter = interval(1000);

// Subscribe to begin publishing values

secondsCounter.subscribe(n =>

console.log(`It's been ${n} seconds since subscribing!`));

Creation Observables from AJAX request


import { ajax } from 'rxjs/ajax';

// Create an Observable that will create an AJAX request

const apiData = ajax('/api/data');

// Subscribe to create the request

apiData.subscribe(res => console.log(res.status, res.response));

Progressive Web App

PWA or Progressive Web App makes you Angular app performance faster. Here the tips how you enable it into your Angular app;

  • Use Angular CLI
  • Add necessary package or service worker using the following command

ng add @angular/pwa --project *project-name*

It will do the following things automatically;

@angular/service-worker package will be added to your project

  • Build support of service worker in the CLI will be enabled
  • Updating index.html along with manifest.json file as well as metadata tags for theme-color
  • You can edit the manifest file

Add;
short_name or name
display
start_url
icons
into the manifest file if you want to make the app installable.

Configuration of Service worker by editing the file

Angular Development Services

For Run-Time Performance

Detach Change Detection

By performing change detection, Angular can detect changes anytime, which requires heavy computational load. This can be changed by setting “ChangeDetectionStrategy” to “OnPush”. At the same time, developers can not only detach the component from change detection, but also developers will have control and inform the app as when and where the change detection should be applicable.

Here’s the example;


import {AfterViewInit, ChangeDetectorRef} from '@angular/core';

@Component(…)

class AppComponent implements AfterViewInit {

constructor(private cdr: ChangeDetectorRef) {}

ngAfterViewInit() {

// We only want to detach the change detectors after change detection has been performed for the first time

this.cdr.detach();

}
update() {

// Run change detection only for this component when update() method is called.

this.cdr.detectChanges();

}

}

Use trackBy instead of ngFor

'ngFor' is a built-in template directive in Angular and it is Generally we used 'ngFor' creating a template for each item in the application. You can use 'trackBy' instead of 'ngFor' which help you by bringing unique and customized identifier each item instead of rendering the whole DOM tree.

How ‘trackBy’ Helps

When using 'ngFor', you need re-render the entire DOM tree after every change occurs in the array while using 'trackBy', you can specify the changes separately and it will help Angular to make DOM changes for the defined array.

Let’s understand this through the example here;

When you use 'ngFor' such as;

Now, each time the changes occur, the whole DOM tree will be re-rendered.

When you use 'trackBy' functions, such as;

Now, it returns as a unique identifier for each item and will be rendered only the selected item.

Use Prod-Mode

Run time perfomance will also get boosting when you enable “enableProdMode()” which will forbade Angular from conducting additional checks for change detection. Here’s how you can invoke this;



import {enableProdMode} from '@angular/core';

if (ENV === 'production') {

enableProdMode();

}

Hire Angular Developers
Final Words

When it comes to your Angular app performance, there’s a lot has been done in advance. The latest release Angular 8 has plenty of new things, upgrades, updates and others to offer. It has been optimized for performance and speed, though you can add a few more things to get it even better.

Most of the things are there taken from personal experience and online supports. Knowing one’s experience helps developers add some additional skills and knowledge and will also help you, developers, and an application giving a pro touch.

Need Consultation?

Put down your query here...

    Saurabh Barot

    Saurabh Barot, the CTO at Aglowid IT Solutions, holds over a decade of experience in web, mobile, data engineering, Salesforce, and cloud computing. Renowned for his strategic vision and leadership, Saurabh excels in overseeing technology strategy, managing data infrastructure, and leading cross-functional teams to drive innovation. Starting with web and mobile application projects, his expertise extends to Big Data, ETL processes, CRM systems, and cloud infrastructure, making him a pivotal force in aligning technology initiatives with business goals and ensuring the company stays at the forefront of technological advancements.

    Related Posts