Speeding Up Angular with Preloading

· 189 words · 1 minute read

The preloading strategy in Angular is all about balancing efficient load times and user experience, enabling your app to load modules in the background while users interact with the application.

In the Angular Lazy Loading Modules post, I explained how to lazy load modules in an Angular app. We found that it sometimes causes issues when navigating. Using the preload strategy, we can mitigate them.

The concept of preloading is rather simple. When you’re using lazy loading (loading modules only when they’re needed), there might be a delay in rendering some parts of the application, especially for larger modules. Preloading counters this by loading the rest of these modules in the background, after the app has loaded the initially necessary modules.

While users are busy interacting with the already loaded parts of your app, the remaining parts load quietly in the background, leading to an overall better user experience.

This is how you can configure preloading in your Angular app’s routing module with the built-in PreloadAllModules strategy, which starts preloading all modules right after the initial app load:

import { PreloadAllModules } from "@angular/router";

RouterModule.forRoot(routes, {
  preloadingStrategy: PreloadAllModules,
});