DEV Community

Cover image for Basics of Angular Lazy Loading
Jozsef
Jozsef

Posted on

2 2

Basics of Angular Lazy Loading

Angular lazy loading means that when the application route loads only those modules will load which is on-demand. If we want to achieve lazy loading it's necessary to break down the application into small separated modules.

It is a very useful built-in angular feature, as the app complexity grows its size is getting bigger and bigger that leads to slow application, especially on mobile!


create application:
ng new lazyloading-demo
create modules
ng g module home
ng g module products

create a separate module for routing paths

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

@NgModule({
  imports: [
    RouterModule.forChild(routes),
  ],
  exports: [RouterModule]
})
export class ProductsRoutingModule { }
Enter fullscreen mode Exit fullscreen mode

import ProductsRoutingModule into products.module.ts and the same thing has to be done for Home module.
Make sure that in routes array has at least one component which point to empty path, that will be the landing page of the module.


const routes: Routes = [
  {path: 'home' , 
     loadChildren : () => import('./home/home.module').
     then(module => module.HomeModule)},
  {path : 'products' , 
    loadChildren : () => import('./products/products.module').
    then(module => module.ProductsModule)}
];

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

Enter fullscreen mode Exit fullscreen mode

When you queryhttp://localhost:4200/home in the network tab you can see that src_app_products_products_module_ts.js loads.

Lazy loading in the metwork tab

You can find this small demo app on this repository!

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more