Demo
PreLoad Strategy
Service
HTML
TS
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.
| ID | Name | |
|---|---|---|
| 10001 | Alice | alice@example.com |
| 10002 | Bob | bob@example.com |
| 10003 | Charlie | charlie@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
- Custom Preloading Strategy: Implement a class that extends
PreloadingStrategy. In thepreloadmethod, check for a custom route data property (e.g.,preloadOnDemand) and return an observable that triggers when your service requests preloading. - Preloading Service: Create a service with a method (e.g.,
triggerPreload(path: string)) that signals your strategy to preload a specific route/module. Use RxJSSubjectorBehaviorSubjectfor communication. - Router Configuration: In your router setup, provide your custom preloading strategy using
withPreloading(CustomPreloadingStrategy)and setdata: { preloadOnDemand: true }on routes you want to support on-demand loading. - Component Integration: Inject your preloading service in the relevant component (e.g., user list). Call the service’s method on a user action (like
mouseenteron a link) to trigger preloading for the target route. - 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.
- Best Practices: Only preload modules that are likely to be needed soon. Avoid preloading everything to preserve bandwidth and performance.
