bg-img

    Created by Maximilian Schwarzmüller
    Last Updated on June 19, 2020

    Lazy loading is an important concept in modern web apps - see my dedicated tutorial for more information about the general idea behind lazy loading.

    To sum it up: Lazy loading allows us to load resources like scripts and images “just in time”, i.e. only when they’re really needed. This can reduce the initial page loading time and also save bandwidth for your users.

    In Angular apps image lazy loading works just as explained in the above article, there’s no Angular-specific implementation of it.

    But when it comes to lazy loading script code, there is a difference. You don’t need to write your own lazy loading code for that - at least not the code shown in the linked article.

    Learn more about lazy loading and Angular in general in my Angular - The Complete Guide course.

    # Which Scripts Can You Load Lazily?

    In Angular apps, you of course write a lot of script code. Components, services, directives etc.

    There are two main kinds of code that you can load lazily in component-focused web apps like the ones you’re building with Angular:

    • Components: Only load component code (and all related code) when a component is rendered to the screen
    • Routes: Only load route component code (and all related code) when a route is visited by the user

    Loading components lazily is a bit tricky in Angular - right now, there isn’t an official, simple, straightforward way of doing so. You can come up with workarounds and creative solutions (like in this article) but typically, you won’t load components lazily.

    This might sound bad but it actually isn’t: Ofen, your components won’t be that huge so you might not even gain too much by loading them lazily.

    You gain more by lazyily loading routes (and the modules they point at) instead.

    In Angular, routes point at modules which in turn then define a bunch of components and directives (and possibly other modules being imported) that make up this module. And all that code can be lazy loaded in one extra chunk if you lazy load the route that points at that module.

    And unlike components, routes can be lazy loaded easily in Angular.

    # How To Add Lazy Loading

    Here’s all the code you need:

    const routes: Routes = [
      {
        path: 'user-profile',
        loadChildren: () =>
          import('./user/user-profile.module').then((m) => m.UserProfileModule),
      },
    ];

    This assume that user-profile.module.ts exports a class named UserProfileModule that is decorated with NgModule.

    Historically, the syntax looked like this by the way:

    const routes: Routes = [
      {
        path: 'user-profile',
        loadChildren: './user/user-profile.module#UserProfileModule'
      },
    ];

    All the rest is handled by Angular and the underlying build workflow tool (e.g. Webpack) - you don’t need to do anything else!