Lazy Loading in Angular: Optimize Your Application’s Performance

Ram Kumar

Ram Kumar

January 8, 20253 min read

Lazy Loading in Angular: Optimize Your Application’s Performance

As Angular applications grow in size, their initial load time can increase significantly. To tackle this, Angular offers a powerful feature called lazy loading, which allows you to load modules on demand, instead of loading them all upfront. By implementing lazy loading, you can improve your application’s performance and provide a better user experience.

In this blog post, we’ll discuss what lazy loading is, its benefits, and how you can implement it in an Angular application using practical examples.

What is Lazy Loading?

Lazy loading is a design pattern that delays the loading of certain resources (like modules, components, or routes) until they are needed. This minimizes the initial bundle size and speeds up the application load time.

In Angular, lazy loading is often implemented using the router to load feature modules only when their corresponding routes are accessed.

Benefits of Lazy Loading

  • Improved Performance: Reduces the size of the initial bundle by deferring the loading of modules not immediately required.
  • Faster Load Time: Decreases the time taken for the initial rendering of the application.
  • Optimized Resource Usage: Loads resources only when they are needed, reducing memory consumption.

Steps to Implement Lazy Loading

Let’s walk through how to implement lazy loading in an Angular application step by step.

1. Set Up Your Angular Application

First, create a new Angular application or use an existing one.

ng new angular-lazy-loading
cd angular-lazy-loading

2. Create Feature Modules

Create feature modules that you want to load lazily. For example, let’s create two modules: AdminModule and UserModule.

ng generate module admin --route admin --module app.module
ng generate module user --route user --module app.module

The --route flag automatically configures lazy loading for these modules in the AppRoutingModule.

3. AppRoutingModule Configuration

When you create modules with the --route flag, Angular automatically sets up the lazy-loaded routes in app-routing.module.ts. Here’s how it looks:

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

const routes: Routes = [
  {
    path: 'admin',
    loadChildren: () =>
      import('./admin/admin.module').then((m) => m.AdminModule),
  },
  {
    path: 'user',
    loadChildren: () =>
      import('./user/user.module').then((m) => m.UserModule),
  },
  {
    path: '',
    redirectTo: '/user',
    pathMatch: 'full',
  },
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
})
export class AppRoutingModule {}

Here:

  • The loadChildren property dynamically imports the modules.
  • The AdminModule and UserModule are loaded only when the user navigates to /admin or /user, respectively.

4. Create Components Inside Feature Modules

Next, add components to your feature modules. For instance, add an AdminDashboardComponent to the AdminModule.

ng generate component admin/admin-dashboard

Similarly, add a UserDashboardComponent to the UserModule.

bashCopyEdit

ng generate component user/user-dashboard

5. Set Up Routing in Feature Modules

Configure the routes for each feature module. For example, in admin-routing.module.ts:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AdminDashboardComponent } from './admin-dashboard/admin-dashboard.component';

const routes: Routes = [
  {
    path: '',
    component: AdminDashboardComponent,
  },
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule],
})
export class AdminRoutingModule {}

Similarly, set up routing in user-routing.module.ts:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { UserDashboardComponent } from './user-dashboard/user-dashboard.component';

const routes: Routes = [
  {
    path: '',
    component: UserDashboardComponent,
  },
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule],
})
export class UserRoutingModule {}

How Lazy Loading Works

When the application starts, only the AppModule and its components are loaded. If a user navigates to /admin, the AdminModule is fetched, loaded, and displayed. Similarly, the UserModule is loaded only when the /user route is accessed.

Bonus: Preloading Lazy-Loaded Modules

While lazy loading improves performance, users may experience a slight delay when accessing a lazy-loaded route for the first time. To mitigate this, Angular offers preloading strategies. Preloading loads lazy-loaded modules in the background after the initial application load.

Enable preloading in the AppRoutingModule:

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

const routes: Routes = [
  {
    path: 'admin',
    loadChildren: () =>
      import('./admin/admin.module').then((m) => m.AdminModule),
  },
  {
    path: 'user',
    loadChildren: () =>
      import('./user/user.module').then((m) => m.UserModule),
  },
  {
    path: '',
    redirectTo: '/user',
    pathMatch: 'full',
  },
];

@NgModule({
  imports: [
    RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules }),
  ],
  exports: [RouterModule],
})
export class AppRoutingModule {}

Conclusion

Lazy loading is a critical optimization technique for large Angular applications. By deferring the loading of feature modules until they’re needed, you can reduce the initial bundle size and improve application performance.

With just a few steps, you can implement lazy loading in your application and take it a step further by using preloading strategies to balance performance and user experience.

Previous: The TypeScript Feature That Changed How I Write React
Next: Mastering Multi-Brand Theming in Angular: Dynamic Themes for Every Brand