Tuesday, November 13, 2018

Preloading modules in Angular

We saw different ways of loading modules in an Angular Application
Eager loading
Laze Loading &
Pre Loading

In Eager Loading the root module and all feature modules are loaded at the beginning when the first request is made, this makes initial loading slow but the subsequent module loading is quick since it is already downloaded to the browser.

In Lazy loading only the root module is loaded on initial request, other modules are loaded when the corresponding route is invoked, here the initial loading is fast, but the subsequent module loads are a bit slow since the module bundle needs to be downloaded before displayed.

Pre Loading is an approach which takes the best of the above 2 approaches, the root module is loaded first when the user views the root module the other modules are loaded in the background so when the user is ready to click the other routes the modules are ready to displayed.

To enable preloading of modules we need to specify this in the module configuration using a preloadingStrategy. We can specify preload all modules (or) pre load no modules in the preloadingStrategy.

@NgModule({
  imports: [RouterModule.forRoot(routes, {preloadingStrategy: PreloadAllModules})],
  exports: [RouterModule]
})

If we want to pre load specific modules then we need to individually specify that in the routing configuration.

const routes: Routes = [
  {
    path: 'feature',
    loadChildren: './feature/feature.module#FeatureModule',
    data: {preload: true}
  },
  {
    path: 'contact',
    loadChildren: './contact/contact.module#ContactModule'
  }
];

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

In the above configuration the feature module will be pre-loaded but the contact module will not be pre-loaded.


Search Flipkart Products:
Flipkart.com

No comments: