We're live-coding on Twitch! Join us!
Lazy Loading in Angular v2+

Lazy Loading in Angular v2+

Code

Application performance is an important part of web development. We always want our users to have the quickest and most performant experience when they visit our apps.

Lazy loading is one of the features we can add to our app to improve performance. What exactly is lazy loading?

Lazy loading is the act of only loading parts of our app when they are needed.

The benefits are:

  • Keep the initial payload small
  • Smaller payloads lead to faster download speeds
  • Lower resource costs especially on mobile networks
  • If a user doesn't visit a section of our app, they won't ever download those resources

The Angular router provides a simple and easy way to add lazy loading to our application. Let's take a look at how we can add it.

Related Video Course: Routing Angular Applications

Overview and Setup

Lazy loading in Angular requires us to format our application a certain way. All the assets that you want to be lazy loaded should be added to its own module.

For instance, if we wanted to lazy load our entire dashboard/ section, we would need to have all those assets/components in their own DashboardModule.

Rules for lazy loading:

  • Move components and assets into their own module
  • DO NOT load the module in the main AppModule
  • Lazy loading will be setup in the main routing file

TLDR: Adding Lazy Loading

Once you have a module you want to lazy load to (let's say a DashboardModule), we can add it to our writing file.

Here is the route to use for a DashboardModule:

const routes: Routes = [
  {
    path: 'dashboard',
    loadChildren: 'app/dashboard/dashboard.module#DashboardModule',
  }
];

We're using the loadChildren parameter to pass a string that points to our module. Make sure you reference from the root src/ folder. Notice we started the string at app/.

The dashboard module will most likely have its own routes. We add the path: dashboard here in the main router and the child router will be set to path: ''.

Now when you visit your dashboard section, you

Building a Lazy Loaded App

Let's build a quick lazy loaded app to see exactly how this would work. We'll be using the Angular CLI. You don't need to using the CLI. Just make sure you have a module and route to it using loadChildren.

We'll create an app with a dashboard section. This dashboard section will be lazy loaded. Not all users will visit the dashboard.

Here's the overview of our app:

  • Home route | '' | HomeComponent
  • Dashboard section | 'dashboard' | DashboardHomeComponent

We'll use the CLI to create the entire app with routing:

# create the app
ng new lazyload-app --routing

# create the home component
ng g component home

# create the dashboard module
ng g module dashboard --routing

# create the dashboard home page
ng g component dashboard/dashboard-home

We now have a clean app setup:

The cool thing about creating a component with the CLI is that the CLI will automatically register the component in its respective module. We don't have to go write the import and add it to the declarations array.

Setup Dashboard Routes

We have our new dashboard module with a new dashboard-routing.module.ts file. This is where we'll define routes. Any routes defined here will be lazy loaded!

Let's update our dashboard-routing.module.ts:

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

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

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

We added path: '' because we'll define the dashboard route in the main router.

Setup Main Lazy Loaded Route

Let's update the main router now to point our dashboard section to this new DashboardModule. We'll also be setting up lazy loading!

// app-routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';

const routes: Routes = [
  {
    path: '',
    component: HomeComponent
  },
  {
    path: 'dashboard',
    loadChildren: 'app/dashboard/dashboard.module#DashboardModule'
  }
];

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

The loadChildren parameter is how we tell Angular to lazy load that section. Remember that we don't have to load the DashboardModule into the main AppModule.

Testing Our App

Now this is all looking good. How do we actually test to see if lazy loading is working? Let's do one last thing before we can test.

To test lazy loading, we'll need a link that points to the dashboard. We need a way to get to our new section we just created.

Open up app.component.html and add the following to the top:

<a routerLink="/dashboard">Dashboard</a>

Starting the App

Now we can start up our app and find out if lazy loading is working.

ng serve --open

Open up dev tools and go to the Network -> JS tab.

As soon as you click the Dashboard link, you'll see the dashboard module get loaded!

Conclusion

Just by adding all our code to a module and adding the loadChildren parameter, the Angular router makes it easy to lazy load sections of our application.

Like this article? Follow @chrisoncode on Twitter