Lazy loading is a technique used for a faster initial load for the angular project. The main idea behind lazy loading is asynchronously loading javascript component. Since the required component is loaded only when the specific router is activated, The initial app size decreased thus increasing the initial load performance.

Lets see how lazy loading in angular works.

Step 1: create a new angular project

 ng new lazy-project --routing

–routing
This creates a separate file named lazy-project-routing.module.ts to store the NgModule’s routes. The file includes an empty Routes object that you can fill with routes to different components and NgModules.

Step 2: create a module name ‘lazy’

ng new module lazy --routing

Step 3: create a LoadMeComponent which needs to be asynchronously loaded

ng g c lazycomponent --module lazy


–module
This adds LazyComponent to the lazy Module.

Now that we are loading lazyComponent using lazy loading technique. Lets first create a route that point to lazyModule.

Step 4: Create a route to lazyModule from app-routing.module.ts

const routes: Routes = [
{
     path: 'lazy',
     loadChildren: './lazy/lazy.module#LazyModule'
   }
 ];

when ‘/lazy URL is fetched in the browser, Angular send the required to the LazyModule.
From the LazyModule we send the request to the LoadMeComponent.

Now , to load the LoadMeComponent we need to add routes to the lazy-routing.module.ts

Step 5: Add path to loadmeComponent from lazy-routing.module.ts

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

Let’s add the url to app.component.html

Step 6: Add link to load the lazy Loading Module(LazyModule) .

<a routerLink="/lazy">Lazy</a>

In the developer tools under network tab, you can see LazyModule only loaded upon click the url which point to ‘/lazy’.

This technique comes in handy when there are a lot of component in the project. Implementing lazy loading helps to reduce the initial loading of the app by asynchronously loading the required component only when specific routes is fetched.

lazy loading in Angular 6

Here is the reference to the project:

https://github.com/rohitsthaa/lazy-loading-angular