Example 12: On-Demand Preloading with Service & Custom Strategy

This demo shows how to preload modules only when triggered (e.g., on hover) using a service and custom PreloadingStrategy. Bandwidth is saved until actually needed.

IDNameEmail
10001Alicealice@example.com
10002Bobbob@example.com
10003Charliecharlie@example.com
  • 1. Open your browser's DevTools and go to the Network tab.
  • 2. Make sure you are on the User List page. The user form module should NOT be loaded yet.
  • 3. Hover over any user ID link in the table above.
  • 4. Watch the Network tab: you should see a new JS chunk (the user form module) being loaded in the background.
  • 5. Clicking the user ID link will navigate instantly to the form, since it was preloaded.
  • 6. If you never hover, the module is never loaded—saving bandwidth.

Setup Instructions: On-Demand Preloading in Angular

  1. Custom Preloading Strategy: Implement a class that extends PreloadingStrategy. In the preload method, check for a custom route data property (e.g., preloadOnDemand) and return an observable that triggers when your service requests preloading.
  2. Preloading Service: Create a service with a method (e.g., triggerPreload(path: string)) that signals your strategy to preload a specific route/module. Use RxJS Subject or BehaviorSubject for communication.
  3. Router Configuration: In your router setup, provide your custom preloading strategy using withPreloading(CustomPreloadingStrategy) and set data: { preloadOnDemand: true } on routes you want to support on-demand loading.
  4. Component Integration: Inject your preloading service in the relevant component (e.g., user list). Call the service’s method on a user action (like mouseenter on a link) to trigger preloading for the target route.
  5. Testing: Use browser DevTools to monitor network requests. Verify that the module is only loaded when you trigger the event (hover/click), not on initial navigation.
  6. Best Practices: Only preload modules that are likely to be needed soon. Avoid preloading everything to preserve bandwidth and performance.