With lazy loading, you can split your angular application into small bundles that can be loaded as required (dynamically). Our list of Angular 2 interview questions has many questions on lazy loading that can get you started on the concept. This means at the start-up; the application will take less time to load since all the bundles (routes) will not be loaded at once.
While using lazy loading, Angular router pre-loads the other parts of the application in the background when the user is interacting with the part of the app that is loaded.
As in other frameworks, lazy loading has several benefits in angular js (check details on Angularjs interview questions), a few of them are listed below-
It is very simple to implement lazy loading in angular –
If you are here, you probably already have angular CLI installed. To know how to install Angular CLI, read our Angular 2 interview questions. If you already have it, just create an empty project on which we will set up lazy loading –
ng new test-lazyload –-routing
The --routing ensures that an additional routing module is set up. Next, create the components from the test-lazyload project –
ng generate component first
This will create a new component and generate all the necessary files inside the folder ‘first.’ Next, create another module for the app and lazy load it. Then we also create a root component for the lazy loaded module –
ng generate module lazy
ng generate component lazy/second
After this, in the app-routing.module.ts
, create an additional route for the LazyModule, where we need not specify the component but just the path to the module and the module class –
const routes: Routes = [
{
path: ‘lazy’;
loadChildren: ‘app/lazy/lazymodule#LazyModule’
}];
And that’s it; we are done with code changes!
(path: '', component: NonLazyComponent)
loadChildren - upon using loadChildren, router passes the value to a registered module loader which fetches the module, extracts the ng module factory and gives it back to the router.
If there are multiple modules and you want one of them to be lazily loaded, call the RouterModule.forChild instead of forRoot for that module.
The next step is to verify if the created module is lazy loaded. For this, you can open developer tools in chrome and click the network tab. Upon navigation to the lazy URL, you will see a chunk file named 0.chunk.js created.
As we see, there are hardly 3-4 steps to enable lazy loading in Angular js. If you want to know more about installing angular and creating simple apps, read angular 2 interview questions on our website. Let us know if you have any doubts through comments.
Angularjs Interview Questions & Answers | Angular 4 Interview Questions |
Angular 6 Interview Questions & Answers | Angular 7 Interview Questions & Answers |
Angular 8 Interview Questions & Answers |