Lazy-load module/scripts/styles in Angular — Part 1

Vishnu Thankappan
3 min readDec 3, 2021

--

Lazy-Load a module

In this we’ll quickly go through how to lazy-load a component in Angular.

  • Create a new angular application using following CLI command

Prod build on the sample application

Prod build on the newly created application

Now for the sake of illustration lets install d3 charts in the application using

Now again run a prod build, now you can see the difference in app bundle size from 219kb to 249kb

Prod build after installing d3

Now lets create two more components using following CLI command:

Now lets add configure d3 chart in DynamicClickLaodPage

And now call the component from app page

Now do ng serve and you should be able to see the chart which you created

d3 chart

Now perform a prod build again and you’ll notice the build size is increased further from 249kb to 272kb as now we are actually importing in into our component.

prod build after using d3 charts

Now let’s start with lazy load where we will load the DynamicClickLaodPage component on demand.

Step-1

  • Generate a module inside DynamicClickLaodPage component folder.
  • This will generate a module file under DynamicClickLaodPage folder
Folder structure

Now remove the declaration of DynamicClickLaodPage from app.module and declare it in DynamicLoadModule

and reconfigure your parent route (in this example app.routing.module.ts ) as below:

lazy loaded route

here, you can see that we are loading DynamicLoadModule when the client hits the route /dynaload

Now when you do a prod build on the application you will observe that the size the the main bundle has been reduced from 273kb to 245kb. and now you can see a section called Lazy Chunk Files here is our newly created module packed separately and will only be loaded once the user calls the route.

It wont seem like a big number now, but when enterprise level app comes into picture, trust me 1kb matters. as it directly impacts the FCP and performance of the overall application.

pre vs post lazy load

Now here for demo I’ve create a button on click of which it will navigate to dynaload page.

When you click on the above button the user is navigated dynaload page and on network section you can see dynamic-click module has been loaded.

dynaload page is loaded on click

And that’s how you can implement lazy loading of modules in Angular.🥳🥳🥳

You can also checkout the sample code in https://github.com/vishnuramero/lazyloading

--

--

Vishnu Thankappan
Vishnu Thankappan

Written by Vishnu Thankappan

A tech enthusiast and a Full Stack developer juggling with ideas

No responses yet