Search code examples
spartacus-storefront

How to prefetch a lazy-loaded feature in Spartacus


There exists a cool library https://github.com/mgechev/ngx-quicklink of Minko Gechev for automatically prefetching Angular lazy loaded routes for links that are visible in the page.

However, the lazy loading of features in Spartacus is not based on routes, but on CMS components. So how can I manually prefetch a lazy-loaded module in Spartacus?

PS. Here are few possible places for prefetch’es, from top of my head:

  • in added-to-cart modal -> prefetch the checkout
  • in homepage -> prefetch product? (and/or prefetch cart)
  • in PDP -> prefetch cart
  • in PLP -> prefetch product? (and/or prefetch cart)

Solution

  • In Spartacus, you can prefetch a lazy-loaded feature module manually, with a little custom code:

    // manual prefetch of CART_BASE_FEATURE lazy loaded feature:
    this.featureModulesService.resolveFeature(CART_BASE_FEATURE).subscribe();
    

    Because the CMS-driven lazy loading in Spartaus is not strictly related to routes, you’d need to implement such prefetch’es deliberately. Preferably following the best practices mentioned also in the README of ngx-quicklink library:

    • wait until the browser is idle (using requestIdleCallback)
    • check if the user isn’t on a slow connection (using navigator.connection.effectiveType) or has data-saver enabled (using navigator.connection.saveData)