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

Vishnu Thankappan
3 min readDec 3, 2021

--

Lazy-Load Scripts and CSS in Angular

source: https://images-na.ssl-images-amazon.com/images/I/41cJwDNjTaL._SX331_BO1,204,203,200_.jpg

How third-party scripts compilation affects the performance of an application and how we can improve the performance of it can be read here:

Here we are going a step further on how we can load a third part script on demand, as-in loading when and where the scripts are actually required.

So, continuing from the old app what I created in the Part-1 of this series

https://vishnuthankappan.medium.com/lazy-load-module-script-styles-in-angular-part-1-cf837f835cfe

Let’s start

  • First we’ll create one component called bootstrap-page using CLI command:

ng g c bootstrapPage

  • generate a module file for the component using CLI command:

ng g m dynamicLoad — flat

  • Now implement lazy-loading to the route to this module:
lazy loaded route
  • For this illustration we’ll be integrating https://getbootstrap.com/ into our component.
  • Here, we have one script and one style link to make bootstrap work.
  • If we paste the above script and style in index.html it will load as soon as user access the page.
loading script and css in index.html
  • Let’s say we don’t want it to load on first page and only want to load as soon as a navigate to bootstrap page.
  • Now, rather than using it in index.html file first we will be creating one service called lazy-script-loader.service.ts where we’ll be writing some code to load script dynamically.

Now that the script loader service is ready. Let’s use angular route resolvers.

In short resolvers take care of tasks that needs to be completed before you navigate to a particular page. You can find more info in https://angular.io/api/router/Resolve

  • create a resolver service using CLI command

ng g resolver loadbootstrapscript

Now, that the resolver is ready, let’s connect it with a route. a resolver service can be connected like shown in the example below:

Once you have connected a resolver service to a route, it basically tell the application to execute the connected service before activating the route.

Now wen you run the application you can see the bootstrap script and styles are not loaded.

Now when you click on the “Load Bootstrap button” you can see the bootstrap class has been loaded and applied styles to the buttons. 🥳

And that’s how you can implement lazy loading of scripts and styles in Angular.🥳🥳🥳

You can refer the entire project here 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