myHotTake

Tag: Faster Angular modules

  • Preloading vs Lazy Loading in Angular: What’s Better?

    If you find this helpful, feel free to like or share so others can enjoy the story too!


    Alright, let me tell you a story. I’m running a small town newspaper, and each of my delivery drivers has their own route. Now, not everyone in the town reads every section—some people love the sports section, others are all about politics, and a few are into the lifestyle column. I want to make sure everyone gets what they want, but I don’t want to exhaust my delivery drivers by sending them out with every single section, every single time. That’d be wasteful, right?

    So here’s what I do: I prep ahead of time based on patterns. I know Mrs. Thompson always reads lifestyle, so I preload that section into her delivery bundle at the start of the day. The Johnson family is big on sports, so I make sure their bundle is ready with the latest scores. By preloading these sections for each route, my drivers don’t have to scramble at the last minute when the demand hits.

    In Angular, modules are like those newspaper sections, and preloading is how I strategically load them into memory. Instead of waiting until someone clicks on “Lifestyle” or “Sports” to fetch the data and load the module, I predict that it might be needed and load it quietly in the background. This doesn’t slow down the homepage delivery but ensures that when someone in the Johnson family opens their sports page, it’s ready and waiting.

    Angular’s preloading strategies—like PreloadAllModules—are like me hiring extra helpers who silently prepare popular sections while I focus on delivering the basics. The result? Faster service, happier readers, and a more efficient system.


    Setting the Stage: Angular Modules

    In Angular, your app might have several feature modules, like a SportsModule or LifestyleModule. By default, these modules are lazy-loaded when a user navigates to a specific route. While this approach saves initial load time, it can lead to delays when users access those routes later. Preloading helps solve this.


    Implementing Preloading in Angular

    Here’s how you can set up preloading in Angular with a simple code example.

    Step 1: Enable Preloading Strategy in the Router

    Use Angular’s built-in PreloadAllModules strategy to preload all lazy-loaded modules.

    import { NgModule } from '@angular/core';
    import { RouterModule, Routes, PreloadAllModules } from '@angular/router';
    
    const routes: Routes = [
      {
        path: 'sports',
        loadChildren: () => import('./sports/sports.module').then(m => m.SportsModule),
      },
      {
        path: 'lifestyle',
        loadChildren: () => import('./lifestyle/lifestyle.module').then(m => m.LifestyleModule),
      },
    ];
    
    @NgModule({
      imports: [
        RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })
      ],
      exports: [RouterModule]
    })
    export class AppRoutingModule { }
    

    Step 2: Optional – Custom Preloading Strategy

    If you want to be more strategic, you can create a custom preloading strategy. For instance, preload only the modules you know will likely be accessed soon.

    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['preload'] ? load() : of(null);
      }
    }
    
    // In the router module
    const routes: Routes = [
      {
        path: 'sports',
        loadChildren: () => import('./sports/sports.module').then(m => m.SportsModule),
        data: { preload: true }
      },
      {
        path: 'lifestyle',
        loadChildren: () => import('./lifestyle/lifestyle.module').then(m => m.LifestyleModule),
        data: { preload: false }
      },
    ];
    
    @NgModule({
      imports: [
        RouterModule.forRoot(routes, { preloadingStrategy: CustomPreloadingStrategy })
      ],
      providers: [CustomPreloadingStrategy],
      exports: [RouterModule]
    })
    export class AppRoutingModule { }
    

    Key Takeaways / Final Thoughts

    1. Preloading Saves Time: By preloading modules, Angular quietly loads feature modules in the background, ensuring users don’t experience delays when navigating.
    2. Flexibility with Strategies: Use PreloadAllModules for simplicity or build a custom strategy to preload only what’s necessary.
    3. Better User Experience: Preloading improves navigation speed, which is especially valuable in apps with multiple routes or when users frequently switch between features.
    4. Keep It Balanced: Preloading too many modules can increase initial load time. Use strategies wisely based on your app’s needs.