Study notes of angular lazy load

Time:2021-7-28

Lazy loading, also known as code splitting, lets you divide your JavaScript code into multiple chunks. The result is that you do not have to load all the JavaScript of the full application when a user accesses the first page. Instead, only the chunks that are required for the given page are loaded.

Lazy loading allows us to split the JavaScript code compiled by typescript into several chunks. In this way, when the application is loaded, we do not need to load all the chunks required by the whole application into the browser, but can implement the on-demand loading mechanism, that is, only the chunks corresponding to the pages to be rendered

In the angular project, execute the command line ng build to view the packaged chunk name and corresponding size, as shown in the following figure.

Study notes of angular lazy load

By default, all components we write in the angular application will be packaged into a main chunk by ng build. For example, I developed a mycartcomponent:

Study notes of angular lazy load

The corresponding JavaScript code after packaging to main chunk is as follows:

Study notes of angular lazy load

How to make the component of an angular application support lazy load, that is, it is packaged separately from main chunk?

Look at an example.

In the apprutingmodule, when configuring routing information, instead of using the conventional component attribute, loadchildren is used to dynamically specify the name of the component to be loaded for a path:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

const routes: Routes = [
  {
    path: 'customers',
    loadChildren: () => import('./customers/customers.module').then(m => m.CustomersModule)
  },
  {
    path: 'orders',
    loadChildren: () => import('./orders/orders.module').then(m => m.OrdersModule)
  },
  {
    path: '',
    redirectTo: '',
    pathMatch: 'full'
  }
];

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

Take a look at the implementation of customers.module.ts:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { CustomersRoutingModule } from './customers-routing.module';
import { CustomersComponent } from './customers.component';

@NgModule({
  imports: [
    CommonModule,
    CustomersRoutingModule
  ],
  declarations: [CustomersComponent]
})
export class CustomersModule { }

Another customersroutingmodule is imported:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { CustomersComponent } from './customers.component';

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

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

Here is the conventional angular router definition mechanism, the combination of path and component field pair.

After ng build is executed, it is found that main chunk, customers and orders chunk are packaged respectively, which indicates that the lazy loading of customers and orders is effective.

Study notes of angular lazy load

Study notes of angular lazy load

Study notes of angular lazy load

It can be seen more clearly when running. When accessing the application in the browser, the corresponding chunk is not loaded because the customers or orders page is not opened:

Study notes of angular lazy load

Click the customers hyperlink:

Study notes of angular lazy load

Until this time, customers chunk was observed, which is the performance effect of angular component lazy loading mode at runtime.

Lazy loading, also known as code splitting, lets you divide your JavaScript code into multiple chunks. The result is that you do not have to load all the JavaScript of the full application when a user accesses the first page. Instead, only the chunks that are required for the given page are loaded. While navigating the storefront, additional chunks are loaded when needed.

Code splitting technology occurs during application build.

Code splitting provided by Angular is typically route-based, which means there is a chunk for the landing page, another chunk for the product page, and so on.

Angular code split is based on routing. For example, landing page assigns a code chunk, product page assigns another code chunk, and so on.

Since Spartacus is mostly CMS driven, the actual application logic for each route cannot be decided at build time. Business users will eventually alter the page structure by introducing or removing components.

In Spartacus, the application logic of each route cannot be known in the build phase, because Spartacus is CMS driven, and business users can affect the page structure by adding or removing components.

Study notes of angular lazy load
Study notes of angular lazy load

ConfigModule.withConfig({
      cmsComponents: {
        BannerComponent: {
          component: () =>
            import('./lazy/lazy-banner.component').then(
              (m) => m.LazyBanner
            ),
        }
      }
    }),

Where is this lazy-lazy-banner-component.js.map? Ng build.

To make code spitting possible, your static JavaScript code (the main app bundle) should not have any static imports to code that you want to lazy load. The builder will notice that the code is already included, and as a result, will not generate a separate chunk for it. This is especially important in the case of importing symbols from libraries.

The measure of lazy load is that the builder generates a separate chunk for code

More Jerry’s original articles are: “Wang Zixi”:
Study notes of angular lazy load