How to Preload Angular Lazy Loaded Modules in the Background
When working with the Angular lazy-loaded modules, have you ever been in a situation where it takes so much time to load, you feel like going for a walk or watch the game of thrones season finale again? I know I have. It gets worse If your lazy module is much larger than the main module. Now it might take more time to load compared to applications’ initial load. Well, if you think, that is just stupid then you are not alone. Lucky for us, Angular team feels the same way. Here, we gonna discuss how to load the lazy modules asynchronously in the background instead of on-demand so at the time user interact with the lazy-loaded modules, it’s already preloaded.
Keep in mind that, it doesn’t mean you’re loading the lazy module on-demand with the main module. NO NO NO !!!, let me be more clear.
Let’s say you have an application with a button that redirects you to a lazy-loaded module. In a typical scenario, the lazy-loaded module starts to get loaded when the user clicks on that button. But with the preload mechanism, the lazy module starts to load soon after the main module gets loaded. So, at the time user interact with the lazy module, it’s already there. Pretty cool right.
Now enough talking and let's dig into coding.
First, you have to, import the PreloadAllModules token from the Angular router package to enable preloading for all lazy-loaded modules. The second argument in the RouterModule.forRoot() method takes an object for additional configuration options. The preloadingStrategy is one of those options. Add the PreloadAllModules token to the forRoot() call.
Now, this looks all good. Although someone might ask “But Sachila, what if I only want to preload one lazy module instead of all”. Well, that’s a good question. If your application has more than one lazy loaded modules then loading all of it might be resource consuming. But don’t worry. As always Angular has the answer.
Angular provides a custom preloading strategy so that developers can explicitly specify which lazy modules they need to preload. All you need to do is set the data.preload flag to true in the lazy-loaded module route and angular take care of the rest.
This strategy is very useful when using the application on mobile devices with low internet bandwidth. This will provide more control to the developer in terms of handing lazy-loaded modules and provide a faster solution to the lazy-loaded modules.