Lazy Loading with Angular
In Angular, lazy loading is a technique that allows you to load JavaScript components and modules asynchronously when a specific route is activated. Lazy loading can help shrink the initial download and enhance performance, especially if you have a large solution with many components with complex routing.
Some of the benefits of lazy loading include:
- Minimize the size of the initial load bundle.
- Load feature areas only when requested by the user.
- Speed up load time for users that only visit certain areas of the application.
Start by creating a new module within your existing application. Determine where you want this module to live within your current structure. For the Sample App, we’re using /src/app/modules. Once navigating to that location in a command prompt, use CLI to create a new module.
C:[path to application root]/src/app/modules>ng g m lazy-load
CREATE src/app/modules/lazy-load/lazy-load.module.ts (192 bytes)
Next create a new components folder within the lazy-load module folder, navigate to it and create a new component using CLI.
C:[path to application root]/src/app/modules/lazy-load/components>ng g c lazy-load
CREATE src/app/modules/lazy-load/component/lazy-load.component.ts (117 bytes)
In your newly created module, import the necessary modules to create a basic page. Then set up a simple route using the ** wildcard so when loading this module it defaults to the root path.
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Routes, RouterModule } from '@angular/router';
import { JhaLayoutModule } from '@jha/jharesponsive/jha-layout';
import { LazyLoadComponent } from './components/lazy-load/lazy-load.component';
const routes: Routes = [
{ path: '**', component: LazyLoadComponent }
];
@NgModule({
declarations: [
LazyLoadComponent
],
imports: [
CommonModule,
RouterModule.forChild(routes),
JhaLayoutModule
]
})
export class LazyLoadModule { }
Once your new module is set up, update the route table in your parent application to include a route definition to the lazy load module.
Instead of specifying a component property, use the loadChildren
property and import the module, supplying the path relative to the app root.
const routes: Routes =
[
{ path: '', redirectTo: '/Home', pathMatch: 'full' },
{ path: 'Home', component: HomeComponent },
...
{ path: 'LazyLoad', loadChildren: () => import('./modules/lazy-load/lazy-load.module').then(m => m.LazyLoadModule)}
];
Finally, create a navigation item pointing to your new module route.
<jha-nav-button jhaIconType="Information" jhaText="Lazy Load Example" jhaTooltip="Example of a lazy loaded module" jhaRouterLink="/LazyLoad"></jha-nav-button>
To confirm it’s working, load your application in a browser. When you navigate to the new /LazyLoad
url, you will see a new js file loaded in the Network tab of your Inspector window.
![Lazy load example](./lazy-load.png)