Sitemap

Preloading Strategy in Angular12

3 min readMay 1, 2022

--

Lazy Loading in angular Application allow us to decrease load time and loading resource on demand.

While this is pretty great for optimization,we can further use preloading strategy .Preloading Strategy makes our intial bundle small at first,once our application is user interactive it starts loading lazy loaded modules in background.

When the user clicks the link, the module has been preloaded already into memory. This mechanism allows Angular to immediately start rendering instead of waiting for the module to download over the network.

There are mainly three options we have while doing preloading strategy

  • PerloadingAllModules
  • NoPreloading
  • CustomPreloading

Let’s understand how they work:

Press enter or click to view image in full size

This is how you set PreloadAllModules.

Similarly you can do for NoPreloading

Press enter or click to view image in full size
NoPreloading

In this case No modules will be preloaded.

Assume that your user is immediately navigating to profile as soon as your page loads,since you have lazily loaded it will take like few second to load,we don’t want that to happen

What we can do is preload that particular profileModule immediately after page render for better user experience

For that we will implement CustomPreloadingStrategy

Get Deepa Chaurasia’s stories in your inbox

Join Medium for free to get updates from this writer.

Now Lets’s see how to achieve this

  • First make configuration in your route , which path you want to preload
Press enter or click to view image in full size
preload to be true

Here we use data property,we can pass any arbitrary data to our route by using data.We pass object to data .Inside object we’ve added customProperty “preload” and we have set it to true.

  • Next you will make a custom-preloaded.ts file
Press enter or click to view image in full size

Here it is implementing abstract method PreloadingStrategy.

If you go to the definition of this method

Press enter or click to view image in full size

You can see it has abstract preload defined there

Back to our customPreloaded what we are actually doing is

  • First we’ll check if give route got data property
  • If yes, then we check whether data has a preload object and is set to true.
  • If both matches then we will preload module, for that we need to return function ,and if any condition is false we use “of method” to return observable null.

In this way our customPreloaded will know if it got this ,preload and if it doesn’t it won’t preload.

That’s how you implement CustomPreloadingStrategy

Thanks for reading ,Like and share please

--

--

Deepa Chaurasia
Deepa Chaurasia

Written by Deepa Chaurasia

Web Developer | Angular | Javascript