React Storefront
|

Prefetching Pages

React Storefront gives you the ability to prefetch pages to make transitions lightning fast.

The react-storefront/Link component can be configured to prefetch content simply by setting the prefetch prop. This prop can have the following values:

  • visible - Only prefetch the page when the link becomes visible. If the link is below the fold, prefetching will only happen when the user scrolls the link into view.
  • always - Always prefetch the page, even if the link is hidden.

For example:

<Link to="/p/1" prefetch="visible">
  Product 1
</Link>

CmsSlot

You can prefetch HTML in CmsSlot elements by calling $.prefetchLinks on each <a> element in your handler and setting the prefetchLinks prop to true:

Handler:

import parse from 'react-storefront-extensions/html/parse'

export default async function somePageHandler(params, request) {
  // ...

  const html = await fetchUpstreamHtml()
  const $ = parse(html)
  $('a').prefetchLinks('visible') // "visible" to fetch when the link is visible or "always" to fetch it immediately

  // ...
}

React Component:

<CmsSlot prefetchLinks>{slot}</CmsSlot>

NavTabs

You can configure react-storefront/NavTabs to prefetch content by setting the prefetch field on MenuItemModel to "visible" or "always" as described above.

prefetch()

You can programmatically prefetch content by calling:

import { prefetch } from 'react-storefront/router/serviceWorker`

prefetch('/path/to/page')

This signals the service worker to prefetch and cache the page.

Prefetching Build Configuration

In order to throttle prefetching, you can set allowPrefetchThrottling to true in your client webpack options. This will instruct the platform to only serve a page if another user has visited it since the cache was last cleared. This prevents all prefetch requests from ever reaching the API and greatly reduces the traffic pressure on the API. This is off by default.

You can also set the amount of time it takes to ramp up prefetching to 100% by using the prefetchRampUpTime webpack option. The default value is 20 mins in milliseconds. This is not necessary if you have allowPrefetchThrottling set to true.