What is lazy loading and How to enable lazy loading in angular 2?
Most of the enterprise application contains various modules for specific business cases. Bundling whole application code and loading will be huge performance impact at initial call. Lazy lading enables us to load only the module user is interacting and keep the rest to be loaded at runtime on demand.
Lazy loading speeds up the application initial load time by splitting the code into multiple bundles and loading them on demand.
Every Angular application must have one main module say AppModule. The code should be splitted into various child modules (NgModule) based on the application business case.
Plunkr Example: Link
- We don't require to import or declare lazily loading module in root module.
- Add the route to top level routing (app.routing.ts) and set loadChildren. loadChildren takes absolute path from root folder followed by #{ModuleName}. RouterModule.forRoot() takes routes array and configures the router.
- Import module specific routing in the child module.
- In the child module routing, specify path as empty string ' ', the empty path. RouterModule.forChild again takes routes array for the child module components to load and configure router for child.
- Then, export const routing:
ModuleWithProviders= RouterModule.forChild(routes);