<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Zeeshan Sarwar on Medium]]></title>
        <description><![CDATA[Stories by Zeeshan Sarwar on Medium]]></description>
        <link>https://medium.com/@zeeshansarwar38?source=rss-6d85190af0c2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*giK3yjrHuyPNn3TSb_GNsw.png</url>
            <title>Stories by Zeeshan Sarwar on Medium</title>
            <link>https://medium.com/@zeeshansarwar38?source=rss-6d85190af0c2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 01:52:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@zeeshansarwar38/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to optimize your Angular Application’s Performance (Part 2)]]></title>
            <link>https://zeeshansarwar38.medium.com/how-to-optimize-your-angular-applications-performance-part-2-5090d65a05be?source=rss-6d85190af0c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/5090d65a05be</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[web-performance]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Zeeshan Sarwar]]></dc:creator>
            <pubDate>Mon, 30 Jan 2023 17:56:27 GMT</pubDate>
            <atom:updated>2023-01-30T17:56:27.015Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KUrXVpd_nAAZbZTTjvclPg.png" /></figure><p>In the first part, I shared some best practices that help to reduce the application load time drastically. If you haven’t read that yet then I will strongly recommend you <a href="https://medium.com/@zeeshansarwar38/how-to-optimize-your-angular-applications-performance-part-1-51b1a5c606d3">read that first</a>.</p><p>Today I will share a few more tips related to app load performance (some of them are not directly related to Angular) and after that, I will focus on techniques to improve the App’s runtime performance. So without further ado, let’s start!</p><h4><strong>NgOptimizedImage Directive</strong></h4><p>Images have become a part of most web applications and handling them properly can lead to a good user experience. The Angular team has introduced a new <a href="https://angular.io/guide/image-directive">NgOptimizedImage</a> directive which helps to ensure best practices are being followed for loading images and improves the image loading speed.</p><h4><strong>WebP Image Format</strong></h4><p>The .webpformat was developed by Google and it is now broadly supported in all major browsers. It is a compressed image format that reduces the file size without affecting the image quality which not only saves the network bandwidth and improves app performance. However, if you are building visual sites like photography or graphic design portfolios and you can’t compromise on image quality even if it’s negligible then you should choose .png or other image formats, other than that I will recommend using images in this format.<br><strong>Note:</strong> This format is not supported on <a href="https://caniuse.com/webp">KaiOS Browser &amp; IE 6– 11</a> so if your users are on these browsers then you will need to add fallback support.<br>You can use &lt;picture&gt;tag for this purpose. Here is the example snippet:</p><pre>&lt;picture&gt;<br>    &lt;source srcset=&quot;image.webp&quot; type=&quot;image/webp&quot;&gt;<br>    &lt;source srcset=&quot;image.jpg&quot; type=&quot;image/jpeg&quot;&gt;<br>    &lt;img src=&quot;image.jpg&quot;&gt;<br>&lt;/picture&gt;</pre><p>This will enable the supported browsers to only load images in .webpformat and unsupported browsers will use .jpg image as a fallback.</p><h4><strong>Browser Resource Hints: Preload, Prefetch, and Preconnect</strong></h4><p>Many modern browsers fetch the required resources (like CSS, JS, and image files) in the best possible order to improve user experience but we developers can predict this in a better way for our web application. So <strong>Resource hints</strong> are basically the HTML code snippets that allow us to do this. You can learn more about it in this <a href="https://medium.com/reloading/preload-prefetch-and-priorities-in-chrome-776165961bbf">great article</a> by <a href="https://medium.com/reloading/preload-prefetch-and-priorities-in-chrome-776165961bbf">Addy Osmani</a>, an engineering manager at Google.</p><p>Now let’s move to how we can improve the app’s runtime performance:</p><h4>Don’t use `constructor` to do any heavy-lifting process</h4><p>In Angular’s official documentation, it is recommended not to use componentconstructor for doing any complex calculations or performing API calls. Instead, constructor should only be used to initialize the local variables to simple values. <br>The reason is that constructor is called every time a component is <br>created, which can lead to excessive network and processing overhead if used for API calls or complex calculations. It can slow down the initial loading of a component, affecting performance and user experience.<br>Instead, the component’s lifecycle hookngOnInit() method should be used for this purpose because it is called after Angular has finished setting up the component’s dependencies and it is only called once when the component is first initialized. This makes it a more efficient place to perform time-consuming operations, compared to the constructor which is called every time the component is created and before its data-bound input properties are set.</p><h4>Web Workers for CPU-intensive computations</h4><p><a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API">Web workers</a> enable JavaScript applications to run CPU-intensive tasks in the background so that the application&#39;s main execution thread can concentrate on the smooth operations of UI. <br>So, if you are building an app that involves a lot of computations, like heavy image processing, data analysis, or scientific simulations, then you should use web workers to boost the app&#39;s performance.</p><h4>Angular CDK: Scrolling Package</h4><p>Displaying thousands of records in the table/list form by using *ngFor loop directive slows down the app performance and results in a poor user experience. If this is the case in your App, then you should use Angular CDK’s scrolling package for implementing virtual scroll. It works by making the height of the container element the same as the height of the total number of elements to be rendered, and then only rendering the items `in view port`.</p><pre>&lt;cdk-virtual-scroll-viewport itemSize=&quot;50&quot; class=&quot;example-viewport&quot;&gt;<br>  &lt;div *cdkVirtualFor=&quot;let item of items&quot; class=&quot;example-item&quot;&gt;{{item}}&lt;/div&gt;<br>&lt;/cdk-virtual-scroll-viewport&gt;</pre><p>So, for example, if you want to display 10K records in your component and only ten records can be visible at a time then it only renders those visible ten elements in the DOM and as the user scrolls down/up it removes those old elements from DOM and adds new ones. This results in a much less number of DOM elements which makes your app faster and more responsive.<br>You can read more on this <a href="https://material.angular.io/cdk/scrolling/overview">here</a>.</p><h4><strong>Don’t use Template Methods</strong></h4><p>Angular framework allows using Template methods for displaying dynamic content. It is a convenient option but it can cause a huge impact on application performance especially if you put heavy computation logic in the template method. This gets even worst when used inside container element with*ngFor directive as shown below:</p><pre>&lt;ul&gt;<br>  &lt;li *ngFor=&quot;let product of products&quot;&gt;<br>      &lt;span&gt; <br>          {{ product.name }} <br>      &lt;/span&gt;<br>      &lt;span&gt; <br>         No. of Reviews {{ getReviewsCount(product) }}<br>      &lt;/span&gt;<br>  &lt;/li&gt;<br>&lt;/ul&gt;</pre><p>The main reason is that Angular executes template methods with every change detection cycle run because it can’t detect what exactly has changed.<br>This problem can be resolved in either of two ways: pre-computing the results or implementing the method as a pure pipe.<br><strong>Solution 1:</strong></p><pre>import { Component, Input, OnInit } from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;app-product-list&#39; ,<br>  templateUrI: &#39;./product-list.component.html&#39;<br>})<br>export class ProductListComponent implements OnInit {<br> @Input() products = [];<br> constructor() { }<br> ngOnInit() {<br>  this.products.map(product =&gt; {<br>    product.numberOfReviews = product.reviews?.length;<br>  });<br> }<br>}</pre><pre>&lt;ul&gt;<br>  &lt;li *ngFor=&quot;let product of products&quot;&gt;<br>      &lt;span&gt; <br>          {{ product.name }} <br>      &lt;/span&gt;<br>      &lt;span&gt; <br>         No. of Reviews {{ product.numberOfReviews }}<br>      &lt;/span&gt;<br>  &lt;/li&gt;<br>&lt;/ul&gt;</pre><p><strong>Solution 2:<br></strong>First, we will create a pure pipe as shown below:</p><pre>import { Pipe, PipeTransform } from &#39;@angular/core&#39;;<br><br>@Pipe({ name: &#39;classCount&#39; })<br>export class ReviewCount implements PipeTransform {<br>  transform(value) {<br>    return value.reviews?.length;<br>  }<br>}</pre><p>Then we can use it in the component’s template:</p><pre>&lt;ul&gt;<br>  &lt;li *ngFor=&quot;let product of products&quot;&gt;<br>      &lt;span&gt; <br>          {{ product.name }} <br>      &lt;/span&gt;<br>      &lt;span&gt; <br>         No. of Reviews {{ product | reviewCount }}<br>      &lt;/span&gt;<br>  &lt;/li&gt;<br>&lt;/ul&gt;</pre><p>Latter has an advantage over the former solution. That is although the pipe is still executed on each change detection cycle the execution benefits from the fact that Angular caches the results of previous executions meaning if a pipe is executed more than once with the same input parameters, then the already cached result is returned, thus boosting up the app’s performance.</p><h4>‘trackBy’ Attribute with `ngFor` Directive</h4><p>MostlyngFor directive is used to display data in the form of a table/list or as &lt;option&gt;in HTMLselectelement and Angular use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is">object identity</a> to track insertions and deletions within the iterator and display those changes in the DOM. The problem with this approach is that when the iterator is produced from an API call to the server, after that API call is re-run, and the value is reassigned to the iterator. Then even if the data hasn’t changed, the second response produces objects with different identities, and in this case Angular tears down the entire DOM and rebuilds it (as if all old elements were deleted and all new elements inserted). As you can imagine this can cause a major performance issue with large collections of data.<br>In order to avoid this problem, it is strongly recommended to use trackBy attribute with ngFor directive. It takes a function that has two arguments: index and itemthen it returns the unique identifier for the current element. This directive allows Angular to track changes by the return value of the function. <br>It reduces the amount of DOM regeneration needed to render any changes.<br>It’s worth mentioning here that trackBy function should be without side effects, and always return the same value for a given input. It should be fast and return unique value for all unique inputs.</p><p>Here is an example:</p><pre>import { Component, Input} from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;app-product-list&#39; ,<br>  templateUrI: &#39;./product-list.component.html&#39;,<br>  styleUrls: [&#39;./product-list.component.scss&#39;]<br>})<br>export class ProductListComponent {<br> @Input() products = [];<br> constructor() { }<br> <br> trackByProductId(index, product) {<br>   return product.id;<br> }<br>}</pre><p>Then we can use this function in a template like this:</p><pre>&lt;ul&gt;<br>  &lt;li *ngFor=&quot;let product of products; trackBy: trackByProductId&quot;&gt;<br>      &lt;span&gt; <br>          {{ product.name }} <br>      &lt;/span&gt;<br>  &lt;/li&gt;<br>&lt;/ul&gt;</pre><h4><strong>`OnPush` Change Detection Strategy</strong></h4><p>As we know the Angular application consists of nested components and by default Angular checks all components for changes on different occasions, even if some components did not change at all. These occasions include network requests, mouse clicks, mouse scrolls, mouse moves, keyboard events, component events, timeouts, intervals, and more. <br>This is the default change detection strategy which causes performance issues as the app size grows and more components are added.</p><p>You can optimize this by switching from defaultto OnPush change detection strategy. It works by changing the behavior of the change detection process for a given component and its children. The change detection process skips the component unless the value of one of its @Input()properties change or the Observable connected to an async pipe in its template receives an update<br><strong>Note:</strong> If the @Input()property is an object then the reference must be updated to the new object in order to trigger the change detection process.</p><p>Here is an example:</p><pre>import { Component, Input, ChangeDetectionStrategy} from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;app-product-list&#39; ,<br>  templateUrI: &#39;./product-list.component.html&#39;,<br>  styleUrls: [&#39;./product-list.component.scss&#39;],<br>  changeDetection: ChangeDetectionStrategy.OnPush<br>})<br>export class ProductListComponent {<br> @Input() products = [];<br> constructor() { }<br> <br>}</pre><p>On the parent store component we will use it like this:</p><pre>import { Component, Input, ChangeDetectionStrategy, OnInit} from &#39;@angular/core&#39;;<br>import { APIService } from &#39;./services/api.service&#39;<br>@Component({<br>  selector: &#39;app-store&#39; ,<br>  templateUrI: &#39;./store.component.html&#39;,<br>  styleUrls: [&#39;./store.component.scss&#39;],<br>})<br>export class StoreComponent implements OnInit {<br> productsList = [];<br> constructor(private apiService: APIService) { }<br> ngOnInit() {<br>  this.apiService.getProducts().subscribe((products) =&gt; {<br>    this.productsList = [...products];<br>  });<br> }<br>}</pre><p><strong>Note: </strong>In the above snippet we used …<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax">spread operator</a> which was introduced in ES6 so if you need to add fallback support then you may use Immutable.js<br>library.</p><p>Next, in our component template we will pass the data to the product list component:</p><pre>&lt;app-product-list [products]=&quot;productsList&quot;&gt;&lt;/app-product-list&gt;</pre><p>Here is another example of using Observable with async pipe:</p><pre>import { Component, Input, ChangeDetectionStrategy, OnInit} from &#39;@angular/core&#39;;<br>import { APIService } from &#39;./services/api.service&#39;<br>@Component({<br>  selector: &#39;app-store&#39; ,<br>  templateUrI: &#39;./store.component.html&#39;,<br>  styleUrls: [&#39;./store.component.scss&#39;],<br>})<br>export class StoreComponent implements OnInit {<br> public productsList$: Observable&lt;Array&lt;Product&gt;&gt;;<br> constructor(private apiService: APIService) { }<br> ngOnInit() {<br>  this.productsList$ = this.apiService.getProducts();<br> }<br>}</pre><pre>&lt;app-product-list [products]=&quot;productsList$ | async&quot;&gt;&lt;/app-product-list&gt;</pre><p><strong>Note: </strong>Direct use of observable with async pipe in the component template gives an added advantage of ‘auto unsubscription’ from observables upon component destruction. That means we don’t need to manually unsubscribe from productsList$observable in ngOnDestroy method.</p><h4>`ngOnChanges`, `ngDoCheck` &amp; other hook methods</h4><p>Angular provides these two hook methods to respond to when it sets or resets data-bound input properties and to detect and act upon changes that it can’t or won’t detect on its own. Also ngDoCheck hook method can be used to define a custom change detection strategy. <br>One should be careful about how much logic or computation to put into these methods because they are called frequently during the change detection process and any long-running logic can hugely impact the application performance.</p><h4><strong>Caching API calls responses</strong></h4><p>It’s more of a general tip that if you are using APIs whose responses change less frequently and are not a security risk then you should cache their responses by using the browser’s cache storage. Alternatively, you can use <a href="https://medium.com/swlh/caching-http-requests-in-angular-using-service-workers-c9d004298cd1">Angular Service Worker</a> for this purpose. This can improve the application performance and user experience.</p><h4>Final words</h4><p>Angular is a performant framework that helps in building scalable and fast web applications. However, as the applications become more feature-enriched and complex, the framework’s default settings don’t remain much effective under some scenarios and they need to be tweaked to remove performance bottlenecks. Today I outlined some techniques that can improve the application’s runtime performance. I hope you will find them helpful in making your app more responsive and fast. <br>If you liked this article then give it a clap and follow me for more content. You can also reach out to me on <a href="http://www.linkedin.com/in/m-zeeshansarwar">LinkedIn</a>. Thanks!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5090d65a05be" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to optimize your Angular Application’s Performance (Part 1)]]></title>
            <link>https://zeeshansarwar38.medium.com/how-to-optimize-your-angular-applications-performance-part-1-51b1a5c606d3?source=rss-6d85190af0c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/51b1a5c606d3</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[angular-performance]]></category>
            <category><![CDATA[service-worker]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Zeeshan Sarwar]]></dc:creator>
            <pubDate>Wed, 11 Jan 2023 08:04:07 GMT</pubDate>
            <atom:updated>2023-01-11T08:04:07.991Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*DiFe1Z_sh2DMgZFs.jpg" /></figure><p>Angular is a performant framework but still, it’s common to see Angular apps getting slower as they grow over time. Before we move on, first let’s elaborate on why we call an app ‘slower’. Most users consider an app slower when it meets any of the following conditions:</p><ol><li>Takes more than 3 to 5 seconds to load and become interactive in a browser</li><li>In-app actions get slower or the app becomes unresponsive</li></ol><p>In the first part of this article series, I will go through a list of best practices that will help us to tackle the first challenge i.e. reducing the app load time.</p><p>You can reduce the application load time by <strong>reducing the app bundle size</strong>,<strong> caching static resources</strong> (JS, Images, and CSS files) <strong>on the client side</strong>, and <strong>effectively implementing both lazy loading and preloading strategies</strong>.</p><p>Let’s discuss these practices one by one.</p><ol><li><strong>Reducing the app bundle size</strong></li></ol><p>You can reduce the app bundle size by following the tips mentioned below:</p><p>1.1 Reducing the number of polyfills that are automatically generated during the build process, can significantly reduce the app bundle size. <br>A <strong>polyfill</strong> is a browser fallback, made in JavaScript, that provides modern functionality to older browsers that don’t support it natively. So if supporting older browsers like IE 11 or older, Opera Mini e.t.c is not of much concern then you can update to Angular version 13 or the latest version.</p><p>Note: Google has officially deprecated support for Internet Explorer 11<br>in <a href="https://blog.angular.io/angular-v13-is-now-available-cce66f7bc296#:~:text=enabled%20by%20Ivy.-,End%20of%20IE11%20support,-We%20heard%20your">Angular 13</a>.</p><p>1.2 If updating to Angular 13+ is not feasible for some reason then you can use the <strong>differential-loading</strong> feature which was introduced back in Angular version 8 (but deprecated in Angular version 13). This feature helps to avoid serving unneeded polyfills to modern browsers.<br>Of course, you do need to update if you are using older than version 8. <br>You can learn more about this feature <a href="https://medium.com/@auth0/a-guide-to-angular-8s-differential-loading-ad08278a7d17">here</a>.</p><p>1.3 Wisely choosing third-party packages for the app can impact build size. Avoid overusing npm/yearn packages for minor benefits if the same functionality can be achieved with fewer lines of code.</p><p>1.4 Write your Angular services in tree-shakeable format. What it means is that the Angular team (starting from version 6) has introduced this new method of providing service to components/modules or services by using this @Injectable decorator. See the following example:</p><pre>import { Injectable } from &#39;@angular/core&#39;;<br><br>@Injectable({<br>  providedIn: &#39;root&#39;,<br>})<br>export class CustomerService {<br>}</pre><p>This will include the service in the app bundle if it’s actually used by a component or service.</p><p>TheprovidedIn property also allows sharing the service between two or more Angular apps that are on the same page. We just need to set its value as platform.</p><pre>import { Injectable } from &#39;@angular/core&#39;;<br>import { CustomerModule } from &#39;./customer.module&#39;;<br><br>@Injectable({<br>  providedIn: &#39;platform&#39;,<br>})<br>export class CustomerService {<br>}</pre><p>1.5 By default Angular eagerly loads the modules/components which results in a larger bundle size. If you are building a large-scale application then you need to break it into smaller and logical modules and then apply lazy loading i.e only load them in the browser when the user actually needs them. This will shorten the application load time.<br>In the following code snippet, we implemented lazy loading for the customer module.</p><pre>// app-routing.module.ts<br>const routes: Routes = [<br>{<br>// Lazyloaded module route<br>  path: &#39;customers&#39;,<br>  loadChildren: &#39;./customers/customers.module#CustomersModule&#39;<br>}];<br>@NgModule({<br>  imports: [<br>    RouterModule.forRoot(routes)<br>  ],<br>  exports: [RouterModule]<br>})<br>export class AppRoutingModule {}</pre><p>Note: Starting from Angular 15, you can build a multi-route application using the new router standalone APIs. You can declare the root route using the following snippet:</p><pre>export const appRoutes: Routes = [{<br>  path: &#39;lazy&#39;,<br>  loadChildren: () =&gt; import(&#39;./lazy/lazy.routes&#39;)<br>    .then(routes =&gt; routes.lazyRoutes)<br>}];</pre><p>lazyRoutes are declared like this:</p><pre>import {Routes} from &#39;@angular/router&#39;;<br><br>import {LazyComponent} from &#39;./lazy.component&#39;;<br><br>export const lazyRoutes: Routes = [{path: &#39;&#39;, component: LazyComponent}];</pre><p>and finally, you have to register the appRoutes in the bootstrapApplication call:</p><pre>bootstrapApplication(AppComponent, {<br>  providers: [<br>    provideRouter(appRoutes)<br>  ]<br>});</pre><p>This provideRouter API is tree-shakable and bundlers can remove the unused features of the router at build-time. Angular team claims that by using this new API, they got an 11% reduction in the size of the router code in the application bundle.</p><p>2.<strong> Pre-loading Modules</strong></p><p>As we discussed that splitting an Angular app into lazy-loaded modules can reduce the app bundle size and improve the application load time. However, there is a caveat that when the user will navigate to the lazy-loadable section of the application, the router will have to fetch the required modules from the server, which can take time. This is where Angular’s built-in ‘pre-loading’ feature comes into play. By using this feature we can enable the router to <strong>preload lazy-loadable modules in the background <em>asynchronously </em>while the app is loaded and interactive in the browser.</strong></p><p>Angular provides two preloading strategies named PreloadAllModules and NoPreloading. You can use one of them or create your own custom strategy.</p><p>NoPreloading strategy is enabled by default which means Angular doesn’t preload any module.</p><p>PreloadAllModules loads all lazy modules immediately after bootstrapping.<br>To enable the preloading of all lazy-loaded modules, import the <a href="https://angular.io/api/router/PreloadAllModules">PreloadAllModules</a> strategy class from <a href="https://angular.io/api/router">angular/router</a>in your AppRoutingModule file and then specify your preloading strategy by usingforRoot()method like this:</p><pre>import { RouterModule, PreloadAllModules } from &#39;@angular/router&#39;;<br>@NgModule({<br>  imports: [<br>    RouterModule.forRoot(routes, {<br>      preloadingStrategy: PreloadAllModules,<br>    }),<br>  ],<br>})<br>class AppRoutingModule {}</pre><p>This preload strategy will preload all modules as quickly as possible.</p><p>If you don’t want to pre-load all lazy-loaded modules or want to build your own pre-load strategy for some other requirements then you can do so by creating a class that should implement this abstract class <a href="https://angular.io/api/router/PreloadingStrategy#preloadingstrategy">PreloadingStrategy</a>. You need to implement its preload method where you can provide your custom logic. <br>In the following example, we will create a strategy that will pre-load only selected modules.</p><pre>mport { Injectable } from &#39;@angular/core&#39;;<br>import { Observable, of } from &#39;rxjs&#39;;<br> <br>import { PreloadingStrategy, Route } from &#39;@angular/router&#39;;<br> <br>@Injectable({<br>  providedIn: &#39;root&#39;,<br>})<br>export class PreloadSelectedModulesStrategy implements PreloadingStrategy {<br>  preload(route: Route, load: () =&gt; Observable&lt;any&gt;): Observable&lt;any&gt; {    <br>    if (route.data &amp;&amp; route.data[&#39;preload&#39;]) {<br>      return load();<br>    } else {<br>      return of(null);<br>    }<br>  }<br>}</pre><p>Then we can utilize this inAppRoutingModuleas in the following example we will pre-load our CustomersModule only:</p><pre>import { NgModule } from &#39;@angular/core&#39;;<br>import { Routes, RouterModule } from &#39;@angular/router&#39;;<br>import { PreloadSelectedModulesStrategy } from &#39;./preload-selected-modules-strategy&#39;;<br> <br> <br>const routes: Routes = [<br>{path: &quot;customers&quot;, loadChildren:&#39;./customers/customers.module#CustomersModule&#39;, data: { preload: true }},  <br>{path: &quot;admin&quot;, loadChildren:&#39;./admin/admin.module#AdminModule&#39;, data: { preload: false }},<br>];<br> <br>@NgModule({<br>  imports: [RouterModule.forRoot(routes, { preloadingStrategy: PreloadSelectedModulesStrategy})],<br>  exports: [RouterModule]<br>})<br>export class AppRoutingModule { }</pre><p>3. <strong>Implement Caching</strong></p><p>You can further improve the application performance for return visitors by implementing server-side and client-side caching. Server-side caching is out of the scope of this article so we will stick with client-side cache implementation. <br>Client-side caching can be implemented in two ways:</p><p>3.1 Using Service Workers for caching<br>3.2 Serving Angular app with caching headers</p><p><strong>Service Workers for caching<br></strong>Angular Service Worker and the Angular CLI’s built-in PWA support makes easy to implement caching for static assets and API requests which gives an almost instant load time. It is worth mentioning that Service Worker can be used for caching without converting an app into PWA. However it is mandatory that application must be accessed over HTTPS, not HTTP.<br>You can learn more in this <a href="https://angular.io/guide/service-worker-getting-started">great article</a> from Angular.</p><p><strong>Serving Angular app with HTTP caching headers<br></strong>Implementation of this caching approach requires control over the web server. This can be achieved in different ways depending on the backend server which you are using. You can learn more about caching headers in this <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Caching">MDN article</a> and it’s <a href="https://web.dev/codelab-http-cache/">implementation in Express</a>.</p><h4><strong>Final Words</strong></h4><p>Today we discussed some best practices to make an Angular App load faster in the browser. In the next part I will share some tips for boosting up the app runtime performance. So follow me on medium and you can also reach out to me on <a href="http://www.linkedin.com/in/m-zeeshansarwar">LinkedIn</a>.<br>May you build performant web apps in this life and hereafter. Amen!🤞😉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51b1a5c606d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>