DEV Community

Cover image for Predictive Preloading Strategy for Your Angular Bundles

Predictive Preloading Strategy for Your Angular Bundles

John Papa on May 31, 2019

Users want fast apps. Getting your JavaScript bundles to your browser as quickly as possible and before your user needs them can make a huge and po...
Collapse
 
dnesteryuk profile image
Dmitriy Nesteryuk

Thanks John, for your series of articles ;) I like the idea a lot. I've been working on a similar idea which might be useful for non-SPA sites. Here is a URL to the project github.com/sirko-io/engine. The project learns how users navigate a site and prefetch pages and assets which users might need next.

Collapse
 
john_papa profile image
John Papa

You’re welcome. Thanks for sharing your project too.

Collapse
 
char_greenman profile image
Charlie Greenman

Just curious, why is the service being included as the preloadingStrategy, as opposed to the OnDemandPreloadStrategy class?

Collapse
 
john_papa profile image
John Papa

Just a name I chose. You could certainly name it the same.

Collapse
 
char_greenman profile image
Charlie Greenman

I think my question wasn't clear enough. My question is different. The service is being included as the preloading strategy. The interface for preloading strategy(angular.io/api/router/PreloadingSt...) specifies that the method to be overridden is preload. However, here you are including the service as the preloading strategy, which uses startPreload. So I'm just trying to figure out how the preloadingStrategy knows to use the service for preloading? Sort of confused how this all working

Thread Thread
 
john_papa profile image
John Papa

I'm not sure I understand, but let me try to see if I follow your question. Angular has the interface PreloadingStrategy which we can implement in a class. This code implements it with export class OnDemandPreloadStrategy implements PreloadingStrategy. So the OnDemandPreloadStrategy must implement the preload method in that interface, which it does with

  preload(route: Route, load: () => Observable<any>): Observable<any> {
    return this.preloadOnDemand$.pipe(
      mergeMap(preloadOptions => {
        const shouldPreload = this.preloadCheck(route, preloadOptions);
        return shouldPreload ? load() : EMPTY;
      })
    );
  }

Then to use this strategy we must specify a class that implements the strategy, so in the router module we specify

RouterModule.forRoot(routes, {
      preloadingStrategy: OnDemandPreloadStrategy
    })

Ah - I think I see your point ... that last line of code in the article had a typo that didn't match my code. I just fixed it to point to the strategy. Thanks!

Thread Thread
 
char_greenman profile image
Charlie Greenman

There we go, that would be it. Thank you.

Collapse
 
bessamhajsalem profile image
bessam-haj-salem

Thanks John for your amasing help to junior developer like me, is there a github repo where we can find this code ? , thank you so much