Loading on Demand: Implementing Lazy Loading in Angular

Boost your application's performance by loading code only when it's needed. Master Angular's most powerful optimization technique.

🚀

Welcome! Let's discover how to make our Angular apps faster with Lazy Loading.

/* Optimizing for speed... */

Why Lazy Loading? The Need for Speed

By default, an Angular application loads all modules at startup. This creates a large initial file (a "bundle") that can slow down the first page load. Lazy loading is a design pattern that splits the app into smaller chunks and loads them only when a user navigates to a specific route.

Configuring Routes for On-Demand Loading

Lazy loading is configured in your routing module (e.g., `app-routing.module.ts`). Instead of using the `component` property for a route, you use `loadChildren` to tell Angular where to find the module to load on demand.

The `loadChildren` Property

The loadChildren property in a route definition is the key to enabling lazy loading. It takes a function that calls a dynamic import. When the user visits the specified `path`, Angular executes this function to fetch and load the required module.

The Dynamic `import()` Syntax

The dynamic import() is a modern JavaScript feature that returns a Promise. This Promise resolves with the requested module. Angular then uses this module to create the components needed for the route. The syntax is typically () => import('./path/to/module').then(m => m.YourModule).

Practice Zone


Interactive Test 1: Match the Concepts

Match the term with its correct description in the context of Angular lazy loading.

Arrastra en el orden correspondiente.


Arrastra las opciones:

loadChildren
import()

Completa el código:

Route Property______
JS Syntax______
Unlock with Premium

Interactive Test 2: Complete the Route

Complete the route configuration to lazy load the `FeatureModule`.

Rellena los huecos en cada casilla.

const routes: Routes = [
  {
    path: 'feature',
    : () => ('./feature/feature.module').then(m => m.FeatureModule)
  }
];
Unlock with Premium

Practice Example: Code Your Own Route

Create a complete `AppRoutingModule` that lazy loads an `AdminModule` at the `/admin` path.

* Write the code below. Correct characters will be shown in green and incorrect ones in red.

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) } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
Unlock with Premium

Knowledge Check

Which of the following is the primary benefit of using lazy loading in Angular?


Unlock with Premium

Advanced Lazy Loading Strategies

Lazy loading is powerful, but Angular offers even more control over how and when your modules are loaded. Understanding these strategies can further enhance your application's performance.


1. Preloading Strategy: The Best of Both Worlds

What if you could load the initial app quickly, and then, while the user is interacting with the first page, silently fetch the other modules in the background? That's exactly what **preloading** does. The user experiences a fast initial load and then seamless, instant navigation to other feature areas.

// in app-routing.module.ts
import { RouterModule, PreloadAllModules } from '@angular/router';

@NgModule({
  imports: [
    RouterModule.forRoot(routes, {
      preloadingStrategy: PreloadAllModules // <-- Enable preloading
    })
  ],
  // ...
})

2. Custom Preloading Strategy

For ultimate control, you can create a custom preloading strategy. For example, you could preload only modules that have a special `data` flag in their route configuration, or preload modules based on the user's connection speed. This allows you to prioritize which features get loaded in the background.

3. When NOT to Lazy Load

Lazy loading is not always the answer. Core, essential modules that are required on startup (like authentication services, navigation bars, or core UI libraries) should be included in the main bundle. Lazy loading these would defeat the purpose and potentially harm the user experience by making essential features slow to appear.


Practical Takeaway: Start with lazy loading for all feature routes. Then, implement a preloading strategy to enhance perceived performance. Always keep core functionality in your eager-loaded main bundle.

Lazy Loading Glossary

Lazy Loading
A strategy to load features as needed. It keeps initial bundle sizes small, which can help decrease load times.
Bundle
The JavaScript files that the Angular CLI produces during the build process. A large initial bundle can slow down your app.
loadChildren
A property of an Angular `Route` that tells the router how to lazy load a module associated with that route.
Dynamic import()
A modern JavaScript syntax that allows you to load a module on demand. It returns a `Promise` that resolves to the module.
Feature Module
An `NgModule` created for a specific business domain or user workflow (e.g., `AdminModule`, `DashboardModule`). These are prime candidates for lazy loading.
Preloading Strategy
A technique where lazy-loadable modules are fetched in the background *after* the initial application has loaded, speeding up subsequent navigations.