Quick Guide to Lazy Loading in Angular


Lazy loading is a popular technique for improving page performance and page load times in web applications. In Angular, lazy loading can be achieved using the routing mechanism built into the framework.

In this article, I’ll explain the basics of lazy loading and show how to wire Angular modules to load only when the user follows a certain route in the application structure.

What is Lazy Loading

Lazy loading is a web development practice in which a resource or object is not loaded or initialized until it is actually needed. The goal is to improve performance and conserve system resources. The most common use case is images that appear “below the fold”—with lazy loading, these images display as a placeholder, and only if the user scrolls down to their location, the full images load.

Lazy loading has several important advantages. It reduces page weight and page load time, which is critical for user engagement, conversion, and search ranking. It can save bandwidth, because resources are not needlessly downloaded to visitor browsers.

Another little-known benefit is that lazy loading conserves system resources, both on the client and server, because images, JavaScript, and other resources on the page may require computing resources to execute, both on client side and server side.

What Can You Load Lazily in Angular?

There are several types of resources you may want to lazy load in Angular applications:

Images

There is no special Angular implementation for lazy loading images. An easy way to do it is via the HTML image tag’s loading attribute, supported by modern browsers, including Chrome 77 and up, but not on Safari (see full support matrix).

The code looks like this:

<img src="image-under-fold.png" loading="lazy" />

If you want to lazy load rich media on other browsers, you’ll need to write custom JavaScript.

Components

Components are a central building block of Angular applications. A component includes an HTML template, a Typescript class, and a CSS selector defining how the component is used.

Lazy loading for components can be difficult—there is no official or straightforward way to do it. There are some workarounds—for example, you could create a component that exists without a module using a framework like Ivy. It would then be easier to lazy load that component. Learn more about that approach in this post.

Routes

Lazy loading routes is a bit easier, and is commonly done in Angular. A route is a module that defines a set of components and directives, and may import other modules. By lazy loading the route, you can also lazy load all the code encompassed by that route, when it is required by the user. Below we’ll explain this approach in more detail.

Quick Tutorial: Lazy Loading Routes in Angular

The tutorial below is based on the lazy-app code example by Thiago Reis (see the full code on Github). We’ll show how to split an application into modules, and load one of the modules lazily using routes.

  1. Create new application with routing enabled

Use this command in the Angular CLI to create an application structure with a route file.

ng new lazy-app --routing

In the app.component.html file, add navigation links to a home component (loaded by default) and a lazy module (which will be loaded only when clicked), like this:

<a routerLink="home">Home Component</a>
<a routerLink="lazy">Lazy Module</a>
  1. Create home component and lazy module

Run the following commands to create the Home component and Lazy module with a component called “sobre”:

ng generate component home
ng generate module lazy --routing
cd src/app/lazy
ng generate component sobre

The Lazy module is defined in the lazy.module.ts file. In this file, we specify that when the module loads, its default route should point to the “sobre” component:

const routes: Routes = [
   {path: '', component: SobreComponent}
];
  1. Define routes

In the app-routing.module.ts configuration file, define routes like this. This code directs the default route to “home” route, and then to the home component, and directs the “lazy” path to the Lazy module.

const routes: Routes = [
  {path: '', redirectTo: 'home', pathMatch: 'full'},
  {path: 'home', component: HomeComponent}
];

In app-routing.module.ts for the lazy module, define routes like this:

const routes: Routes = [
  {path: '', redirectTo: 'home', pathMatch: 'full'},
  {path: 'home', component: HomeComponent},
  {path: 'lazy', loadChildren: './lazy/lazy.module#LazyModule'}
];
  1. Run the app with lazy loading behavior

Run the app from the code example and view the homepage. There are two navigation links—Home Component and Lazy Module. Test lazy loading behavior as follows:

  • Immediately after the app loads, check Chrome Dev Tools to see that only the Home component and Angular Javascript files are initially loaded.

  • Click the Lazy Module link and see that “lazy-lazy-module.js” is loaded.

That’s it! You created a simple application that reduces load time, by removing one Angular module from the bootstrapping process, and only running it when a user requests it.

Conclusion

In this article, I showed how to achieve lazy loading in Angular. I presented a quick tutorial showing how to lazy load a route in four steps:

  1. Create a new Angular application with routing enabled

  2. Create a “home” component and a “lazy” component you want to load conditionally

  3. Define routes specifying when the lazy component should be loaded

  4. Run the app with the lazy loading behavior and test that only when the user performs the specified action, is the “lazy” component loaded

I hope this will help you create higher performance Angular applications, make users happier, and improve the overall results of your web applications.