DEV Community

Cover image for Basics of Angular Lazy Loading

Posted on


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}

  imports: [
  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)}

  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!

Top comments (0)

50 CLI Tools You Can't Live Without

The top 50 must-have CLI tools, including some scripts to help you automate the installation and updating of these tools on various systems/distros.