Placeholder canvas

What is Lazy Loading and Preloading: When to Use Each for Optimal Performance

Both lazy Loading and Preloading go hand in hand. Both are designed to improve the performance of a website and load a site faster and with reduced latency, with their pros and cons. 

Understanding the differences between these two and knowing when to use each can significantly enhance your site’s user experience and efficiency.

So, if you want to increase your website’s performance, then keep reading.

What is Lazy loading?

Lazy Loading is the method of postponing the Loading or initialization of resources or objects until they are needed in order to increase performance and save system resources. 

For example, if a web page contains an image that the user must scroll down to view, you can display a placeholder and lazy load the complete image only when the user reaches its location.

Lazy Loading

The advantages of lazy Loading are:

  • Reduces initial load time – Lazy Loading of a webpage reduces page weight, resulting in a faster page load time.
  • Bandwidth conservation – Lazy Loading saves bandwidth by delivering material to users only when it is requested.
  • System resource conservation – Lazy Loading saves server and client resources by rendering or executing only a subset of the pictures, JavaScript, and other code.

What is a Preloader?

A preloader is a dynamic element that appears while the website’s content is loading. They inform users that they will need to wait until the complete page is available. 

The goal of preloaders is to improve the user experience by making Loading time feel faster and minimizing uncertainty about whether the website is responsive or not.

Example: Site preload even before complete loading.

Preloader

There are several significant elements of preloaders:

  • Visual Feedback – It displays the loading process through animations, spinners, or progress bars. This helps to manage user expectations and keep them interested.
  • Loading Material – This can apply to a variety of material kinds, including photos, videos, scripts, and specific page components.
  • Design Customization- customize according to their site’s design. They can select colors, animations, and styles that are consistent with branding.
  • Code Implementation – Often uses HTML, CSS, and JavaScript to track the loading progress.
  • Responsiveness – It is critical not to impede user engagement on a website. Preloaders should fade out once all content on a page has been fully loaded and is ready to utilize.

What Preloading is used for?

Preloading reduces page load time by instructing browsers which resources to prioritize. Preloading is often utilized for crucial resources that slow down a page’s Loading time since they are discovered after other resources.

Browsers have improved their ability to identify and load resources more swiftly in recent years. As a result, the preload attribute is now used less frequently, only for resources that rely on reLoading to improve page speed.

When should you use lazy Loading?

The scenario for Lazy Loading is quite easy and straightforward. In a large-scale web application, we can load all modules that are not needed when the program starts.

Preloading is less popular in web application development than Eager Loading and Lazy Loading. Based on my understanding of this Loading approach, Preloading would be preferable in two instances.

  • Case 1: Medium-sized application. In this circumstance, we can speed up the application’s startup by Loading all other modules that are not required to operate the application. Furthermore, because the application will load all of these modules once it has started, it will be more responsive to user requests than if it used the Lazy Loading technique.
  • Case 2: Specific modules that users are likely to use after the program has started. In this circumstance, we can pre-load these feature modules while lazy Loading other modules.

Lazy Loading Implementation

File Structure

The file structure for implementing lazy Loading is as follows:

Step 1: Create Navigation Routes

In lazy-loading-home.component.html, create navigation links to the two child components:

<h3>This is From Lazy Loading Module</h3>

<div class="row">

  <div class="col-sm-4">

    <a routerLink="child1">Lazy Child1</a>

  </div>

  <div class="col-sm-4">

    <a routerLink="child2">Lazy Child2</a>

  </div>

</div>  

<div>

  <router-outlet></router-outlet>

</div>

Step 2: Register Lazy Loading Components

In lazy-loading-routing.module.ts, register the lazy Loading components using the forChild strategy:

r/core';

import { CommonModule } from '@angular/common';

import { Routes, RouterModule } from '@angular/router';

import { Child1Component } from './lazy-loading-home/child1/child1.component';

import { Child2Component } from './lazy-loading-home/child2/child2.component';

import { LazyLoadingHomeComponent } from './lazy-loading-home/lazy-loading-home.component';

const routes: Routes = [

  { path: '', component: LazyLoadingHomeComponent, children: [

    { path: '', redirectTo: 'child1', pathMatch: 'full' },

    { path: 'child1', component: Child1Component },

    { path: 'child2', component: Child2Component }

  ]},

  { path: '**', redirectTo: '' }

];

@NgModule({

  declarations: [],

  imports: [

    CommonModule,

    RouterModule.forChild(routes)

  ],

  exports: [

    RouterModule

  ]

})

export class LazyLoadingRoutingModule { }
import { NgModule } from '@angula

Step 3: Declare Components and Import Module

In lazy-loading.module.ts, declare all lazy Loading components and import the LazyLoadingRoutingModule:

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

import { CommonModule } from '@angular/common';

import { LazyLoadingHomeComponent } from './lazy-loading-home/lazy-loading-home.component';

import { Child1Component } from './lazy-loading-home/child1/child1.component';

import { Child2Component } from './lazy-loading-home/child2/child2.component';

import { LazyLoadingRoutingModule } from './lazy-loading-routing.module';

@NgModule({

  declarations: [

    LazyLoadingHomeComponent,

    Child1Component,

    Child2Component

  ],

  imports: [

    CommonModule,

    LazyLoadingRoutingModule

  ]

})

export class LazyLoadingModule { }

Step 4: Add Route in App Routing Module

Finally, add a route for the LazyLoadingModule in app-routing.module.ts using the loadChildren property:

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

import { Routes, RouterModule } from '@angular/router';

import { EagerHomeComponent } from './features/eager-loading-module/eager-home/eager-home.component';

import { EagerChild1Component } from './features/eager-loading-module/eager-home/eager-child1/eager-child1.component';

import { EagerChild2Component } from './features/eager-loading-module/eager-home/eager-child2/eager-child2.component';

const routes: Routes = [

  { path: '', redirectTo: 'eager-loading', pathMatch: 'full' },

  { path: 'eager-loading', component: EagerHomeComponent, children: [

    { path: '', redirectTo: 'child1', pathMatch: 'full' },

    { path: 'child1', component: EagerChild1Component },

    { path: 'child2', component: EagerChild2Component },

    { path: '**', redirectTo: 'child1' }

  ]},

  { path: 'lazy-loading', loadChildren: './features/lazy-loading-module/lazy-loading.module#LazyLoadingModule' },

  { path: '**', redirectTo: 'eager-loading' }

];

@NgModule({

  imports: [RouterModule.forRoot(routes)],

  exports: [RouterModule]

})

export class AppRoutingModule { }

Important Note

Do not import the LazyLoadingModule in app.module.ts, as it will be eagerly loaded instead of lazily loaded.

Preloading Implementation

File Structure

The file structure for implementing the Preloading module is as follows:

Step 1: Define Preloading Route

Begin by adding the Preloading route to app-routing.module.ts:

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

import { Routes, RouterModule } from '@angular/router';

import { EagerHomeComponent } from './features/eager-loading-module/eager-home/eager-home.component';

import { EagerChild1Component } from './features/eager-loading-module/eager-home/eager-child1/eager-child1.component';

import { EagerChild2Component } from './features/eager-loading-module/eager-home/eager-child2/eager-child2.component';

import { CustomPreloadingStrategy } from './core/custom-preloading-strategy';

const routes: Routes = [

  { path: '', redirectTo: 'eager-loading', pathMatch: 'full' },

  {

    path: 'eager-loading', component: EagerHomeComponent, children: [

      { path: '', redirectTo: 'child1', pathMatch: 'full' },

      { path: 'child1', component: EagerChild1Component },

      { path: 'child2', component: EagerChild2Component },

      { path: '**', redirectTo: 'child1' }

    ]

  },

  {

    path: 'lazy-loading',

    loadChildren: './features/lazy-loading-module/lazy-loading.module#LazyLoadingModule'

  },

  {

    path: 'pre-loading',

    loadChildren: './features/pre-loading-module/pre-loading.module#PreLoadingModule',

    data: { applyPreload: true } // Apply custom Preloading strategy

  },

  { path: '**', redirectTo: 'eager-loading' }

];

@NgModule({

  imports: [RouterModule.forRoot(routes,

    { preloadingStrategy: CustomPreloadingStrategy }

  )],

  exports: [RouterModule]

})

export class AppRoutingModule { }

Step 2: Implement Custom Preloading Strategy

Next, implement the CustomPreloadingStrategy class using the PreloadingStrategy interface:

import { PreloadingStrategy, Route } from '@angular/router';

import { Observable, of } from 'rxjs';

export class CustomPreloadingStrategy implements PreloadingStrategy {

  preload(route: Route, load: () => Observable<any>): Observable<any> {

    return route.data && route.data.applyPreload ? load() : of(null);

  }

}

Step 3: Provide Custom Preloading Strategy

Lastly, provide the CustomPreloadingStrategy in app.module.ts:

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

import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';

import { AppComponent } from './app.component';

import { CustomPreloadingStrategy } from './core/custom-preloading-strategy';

@NgModule({

  declarations: [

    AppComponent

  ],

  imports: [

    BrowserModule,

    AppRoutingModule

  ],

  providers: [

    CustomPreloadingStrategy // Provide the custom Preloading strategy

  ],

  bootstrap: [AppComponent]

})

export class AppModule { }

Explanation

In the provided code:

  • Step 1: Define the routes in app-routing.module.ts, including a route for Preloading with loadChildren pointing to PreLoadingModule. Additionally, a data property should be added to specify that the custom preloading strategy (CustomPreloadingStrategy) should be applied.
  • Step 2: The CustomPreloadingStrategy class implements the PreloadingStrategy interface. It checks if a route has data.applyPreload set to true. If true, it preloads the module using the load() function; otherwise, it returns an observable of null.
  • Step 3: In app.module.ts, provide CustomPreloadingStrategy as a provider to make it available throughout the application for handling custom Preloading logic.

Conclusion

Lazy Loading and Preloading are two tactics used in Angular apps to improve speed by controlling how and when modules are loaded. Understanding the distinctions between these tactics enables developers to make informed decisions that improve user experience and application efficiency.

Lazy Loading delays the Loading of non-critical portions or modules in an application until the user navigates to them. This reduces the amount of JavaScript loaded at the start, resulting in faster initial Loading times. 

It is best suited for applications with extensive feature sets or modules that are not immediately required when the program loads. Lazy Loading can dramatically reduce the initial load time of an application, making it more responsive and efficient.

FAQs on Lazy Loading and Preloading

Can I apply both lazy loading and preloading to an Angular app?

Yes, Angular allows you to use both lazy and Preloading strategies in your application. You can lazy load modules that are less critical for initial load and preload modules that will be accessed soon after the program starts or dependent on user interactions.

How do lazy Loading and Preloading impact application performance?

Lazy Loading and Preloading improve application speed by optimizing resource utilization. Lazy Loading shortens initial load times by postponing non-essential module loading, whereas Preloading boosts perceived performance by Loading predicted modules in the background.

Want faster WordPress?

WordPress Speed Optimization

Try our AWS powered WordPress hosting for free and see the difference for yourself.

No Credit Card Required.

Whitelabel Web Hosting Portal Demo

Launching WordPress on AWS takes just one minute with Nestify.

Launching WooCommerce on AWS takes just one minute with Nestify.