Complement traditional pre-capture techniques with service workers.
Updated
Network reliability
La realización de una tarea en un sitio suele implicar varios pasos. Por ejemplo, comprar un producto en un sitio Web de comercio electrónico puede implicar buscar un producto, seleccionar un artículo de la lista de resultados, agregar el artículo al carrito y completar la operación mediante el pago.
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 para almacenar en cache la respuesta HTML para una solicitud de navegación. Normalmente deberían satisfacerse a través de la red, con Cache-Control: no-cache
, para garantizar que el HTML, junto con la cadena de solicitudes de red posteriores, be (razonablemente) actualizado. Tener que ir en contra de la red cada vez que el Username navega a una nueva página significa, desafortunadamente, que cada navegación puede ser lenta; al menos, significa que no será 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:
Los archivos precargados se solicitan con la prioridad «más baja» y se almacenan en la caché HTTP or in the Cache (dependiendo de si el recurso se puede almacenar en caché o no), durante un período de tiempo que varía según los browsers. Por ejemplo, a partir de Chrome 85, este valor es de 5 minutos. Los recursos se mantienen durante cinco minutos, después de los cuales el 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.
As a result of this, more than 3 weeks of observation Virgilio Sport witnessed the improvement of loading times for navigation to articles. 78%y aumenta el número de impressions de artículos 45%.
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.
En los siguientes casos, la captura previa se utiliza para lograr un target similar al de la captura previa: hacer que la navegación sea más rápida.
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
El almacenamiento en caché de los activos estáticos que las diferentes secciones del sitio podrían utilizar (por ejemplo, JavaScript, CSS, etc.) es una práctica recomendada general y puede dar un impulso adicional en los escenarios de búsqueda previa.
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" ace="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 se utiliza para obtener una página de producto con una strategy de almacenamiento en caché en tiempo de ejecución de Workbox.
To implement that:
- Add a
tag to page:
<link rel="prefetch" href="/phones/smartphone-5x.html" ace="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.
En algunos casos, sin embargo, puede ser mejor delegar esta tarea por completo al trabajador del servicio. Por ejemplo: para precargar los primeros productos en una página de lista de productos renderizada del lado del client, es posible que deba inyectar varios etiquetas dinámicamente en la página, según una respuesta de la API. Esto puede consumir momentáneamente tiempo en el hilo principal de la página y dificultar la implementación.
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 ():
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') {
}
});