Skip to main content

Complement traditional pre-capture techniques with service workers.


Updated

It appears in:
Network reliability

Completing a task at a site usually involves several steps. For example, purchasing a product on an e-commerce website may involve searching for a product, selecting an item from the results list, adding the item to the cart, and completing the transaction by checking out.

In technical terms, moving through different pages means doing a navigation request. As a general rule, do not I want to use long-lasting Cache-Control headers to cache the HTML response for a browse request. They should normally be satisfied over the network, with Cache-Control: no-cache, to ensure that the HTML, along with the chain of subsequent network requests, is (reasonably) up to date. Having to go against the net every time the user navigates to a new page means, unfortunately, that each navigation can be slow; at least, it means it won't be surely Quick.

To speed up these requests, if you can anticipate user action, you can request these pages and assets in advance and keep them in the cache for a short period of time until the user clicks on these links. This technique is called prefetch and is commonly implemented by adding Tags to pages, indicating the resource to search previously.

In this guide we will explore different ways in which service workers it can be used as a complement to traditional pre-breeding techniques.

Production cases

Free market It is the largest e-commerce site in Latin America. To speed up browsing, they dynamically inject labels in some parts of the flow. For example, on list pages, they get the following page of results as soon as the user scrolls to the bottom of the list:

mercadolibre-prefetch-6374544

Preloaded files are requested with the "lowest" priority and stored in the HTTP cache or in the Cache (depending on whether the resource can be cached or not), for a period of time that varies between browsers. For example, as of Chrome 85, this value is 5 minutes. Resources are held for five minutes, after which time the Cache-Control the rules for the resource apply.

Using service worker caching can help you extend the lifespan of prefetch resources beyond the five minute window.

For example, Italian sports portal Virgilio Sport uses the service workers to preview the most popular posts on your home page. They also use the Network Information API to avoid pre-capture for users who are on a 2G connection.

virgilio-sport-logo-8042597

As a result of this, more than 3 weeks of observation Virgilio Sport witnessed the improvement of loading times for navigation to articles. 78%and increases the number of article impressions 45%.

virgilio-sport-prefetch-3369540

Implement caching with Workbox

In the next section we will use Workbox to show how to implement different caching techniques in the service worker that can be used as a complement to , or even a replacement, delegating this task entirely to the service worker.

Caution: You need to take steps to ensure that adding a service worker to your site doesn't actually end up slowing down your browsing. Starting the service worker without using it to respond to a browse request will introduce a small amount of latency (as explained in Building faster, more resilient applications with service workers). You can mitigate this overhead by enabling a function called navigation preload, and then using the network response that has been preloaded within your recovery event handler.

1. Pre-cache static pages and page sub-resources

Pre-caching is the ability of the service worker to cache files while it is being installed.

Precaching sounds similar to preloading, but it's a different technique. In the first, the service worker finds and stores resources (usually static files) while it installs and keeps them in the cache until a new version of the file is available. In the second, resources are requested in advance to have it in the cache for short periods of time in order to speed up subsequent navigation.

In the following cases, pre-capture is used to achieve a similar goal as pre-capture: to make browsing faster.

Static page precaching

For pages that are generated at compile time (eg. about.html, contact.html), or on completely static sites, one can simply add the site's documents to the precache list, so they are already available in the cache each time the user accesses them:

workbox . precaching . precacheAndRoute ( [
{ url : '/about.html' , revision : 'abcd1234' } ,
] ) ;

Precaching page sub-resources

Caching static assets that different sections of the site might use (eg JavaScript, CSS, etc.) is a general best practice and can give an extra boost in pre-search scenarios.

To speed up navigation on an e-commerce site, you can use tags on listing pages to preview product detail pages for the first few products on a listing page. If you have already cached child resources on the product page, this can make browsing even faster.

To implement this:

  • Add a tag to page:

 < link rel = " prefetch " href = " /phones/smartphone-5x.html " as = " document " >

  • Add the child resources of the page to the pre-check list in the service worker:

workbox . precaching . precacheAndRoute ( [
'/styles/product-page.ac29.css' ,
] ) ;

2. Extend the useful life of pre-fundraising resources

As mentioned earlier, fetches and holds the resources in the HTTP cache for a limited period of time, after which the Cache-Control the rules for a resource apply. As of Chrome 85, this value is 5 minutes.

Service workers allow you to extend the life of prefetch pages, while providing the added benefit of making those resources available for offline use.

In the example above, you could complement the used to get a product page with a Workbox runtime caching strategy.

To implement that:

  • Add a tag to page:

 < link rel = " prefetch " href = " /phones/smartphone-5x.html " as = " document " >

  • Implement a runtime caching strategy in the service worker for these types of requests:

new workbox . strategies . StaleWhileRevalidate ( {
cacheName : 'document-cache' ,
plugins : [
new workbox . expiration . Plugin ( {
maxAgeSeconds : 30 * 24 * 60 * 60 ,
} ) ,
] ,
} ) ;

In this case, we have chosen to use a outdated strategy while being revalidated. In this strategy, pages can be requested from both the cache and the network, in parallel. The response comes from the cache if available, otherwise from the network. The cache is always kept up-to-date with the response from the network with each successful request.

3. Delegate prior recruitment to the service worker

In most cases, the best approach is to use . The label is a resource suggestion designed to make pre-capture as efficient as possible.

In some cases, however, it may be better to delegate this task entirely to the service worker. For example: to preload the first products into a client-side rendered product list page, you may need to inject several tags dynamically on the page, based on a response from the API. This can momentarily consume time in the main thread of the page and make implementation difficult.

In cases like this, use a "page to service worker communication strategy" to delegate the preload task entirely to the service worker. This type of communication can be achieved using worker.postMessage ():

page-to-sw-1722362

the Workbox window package it simplifies this type of communication, abstracting many details from the underlying call that is being made.

Prefetch with the Workbox window can be implemented as follows:

  • On page: call the service worker and pass the message type and list of URLs to pre-search:

const wb = new Workbox ( '/sw.js' ) ;
wb . register ( ) ;

const prefetchResponse = await wb . messageSW ( { type : 'PREFETCH_URLS' , urls : [] } ) ;

  • In the service worker: Implement a message handler to emit a fetch () request for each url to search previously:

addEventListener ( 'message' , ( event ) => {
if ( event . data . type === 'PREFETCH_URLS' ) {
}
} ) ;

R Marketing Digital