myHotTake

Tag: Angular deferred module loading

  • Lazy Loading in Angular: A Beginner-Friendly Guide

    If this story helps you understand lazy loading in Angular better, feel free to like or share it with someone who’s curious about Angular concepts!


    I’m the proud owner of a magical backpack. This isn’t an ordinary bag—it’s enchanted to hold a lot of stuff, from a tent to snacks to tools. But here’s the catch: I don’t carry everything around at once. That’d be way too heavy and exhausting, right? Instead, my magical backpack only pulls out the item I need, exactly when I need it.

    Here’s how it works. Say I’m walking through the forest, and it starts to rain. I simply ask my backpack for an umbrella, and poof, it appears in my hand. Later, if I need a flashlight, the backpack gets me that too—on demand. Until then, the umbrella, the flashlight, and all the other items stay neatly packed away, out of sight, saving me energy.

    This is exactly what lazy loading does in Angular. It’s like that magical backpack. My Angular app doesn’t load every single feature upfront because that would make the app feel slow and bulky. Instead, it loads modules (like features or pages) only when they’re needed.

    For example, say my app has a user profile page, but I’m currently on the homepage. The profile page’s code won’t load until I navigate to it. Once I do, Angular retrieves just that piece of code and shows the profile page, just like my magical backpack pulling out the umbrella when it rains.

    To make this magic work in Angular, I use the Router and configure it with a loadChildren property. It’s like telling the backpack, “Only grab the tent if we’re camping.” In the routing module, I specify which features should load lazily, and Angular handles the rest.

    Lazy loading makes my app lighter, faster, and just as magical as my trusty backpack. 🧳✨


    Step 1: Setting Up Lazy Loading

    Imagine I have an Angular app with two modules: HomeModule and ProfileModule. I don’t want to load ProfileModule unless the user navigates to the profile page. Here’s how I set it up.

    app-routing.module.ts

    import { NgModule } from '@angular/core';
    import { RouterModule, Routes } from '@angular/router';
    
    const routes: Routes = [
      {
        path: '',
        loadChildren: () => import('./home/home.module').then(m => m.HomeModule), // Lazy-load HomeModule
      },
      {
        path: 'profile',
        loadChildren: () => import('./profile/profile.module').then(m => m.ProfileModule), // Lazy-load ProfileModule
      }
    ];
    
    @NgModule({
      imports: [RouterModule.forRoot(routes)],
      exports: [RouterModule]
    })
    export class AppRoutingModule {}
    

    Here, the loadChildren property is the magic wand that signals lazy loading. Instead of importing ProfileModule directly, it uses a dynamic import() statement to load it only when the user navigates to the /profile route.


    Step 2: Structuring Modules

    Now, I make sure my ProfileModule is ready to be loaded lazily.

    profile.module.ts

    import { NgModule } from '@angular/core';
    import { CommonModule } from '@angular/common';
    import { RouterModule, Routes } from '@angular/router';
    import { ProfileComponent } from './profile.component';
    
    const routes: Routes = [
      { path: '', component: ProfileComponent }, // Default route for the module
    ];
    
    @NgModule({
      declarations: [ProfileComponent],
      imports: [
        CommonModule,
        RouterModule.forChild(routes) // Configure child routes
      ]
    })
    export class ProfileModule {}
    

    This module is lightweight and self-contained, perfect for lazy loading. The key is using RouterModule.forChild() to set up its routes.


    Step 3: Experience the Magic

    When the app starts, the HomeModule is loaded immediately because it’s the default route. But if I navigate to /profile, Angular dynamically fetches the ProfileModule code in the background and renders the profile page.


    Key Takeaways / Final Thoughts

    1. Why Lazy Loading? It speeds up the initial load time of your app by loading only essential modules upfront.
    2. How Does It Work? Lazy loading relies on dynamic import() statements to fetch code modules only when needed.
    3. Angular Routing Setup: Use loadChildren in your Routes array to enable lazy loading for specific modules.
    4. Structure Matters: Each lazily loaded module should be self-contained, with its own forChild routes.