Complement traditional pre-capture techniques with service workers.
Updated
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 headersConcepto de Encabezados¿Qué son los Encabezados?Los Encabezados, además conocidos como headers en inglés, son una parte fundamental del diseño de cualquier web, dado que consiste en la parte principal que se ve de esta al acceder, la parte de arriba de cualquier página. El lugar más visible y al que todos los usuarios que visitan un lugar de Internet acceden cuando entran en él, pudiendo tener así una imagen rápida plus para almacenar en cacheUn caché es un tipo de memoria auxiliar de la que se puede recuperar a alta velocidad con una capacidad de almacenamiento relativamente pequeña. Se encuentra entre la unidad central de procesamiento (CPU) y la memoria principal. Ayuda a evitar el acceso al disco duro o los recálculos complejos almacenando temporalmente ciertos datos y haciéndolos disponibles rápidamente cuando sea necesario. El caché almacena una copia de la petición actual y plus la respuesta HTMLHTML (Hypertext Markup Language) se usa para estructurar el contenido de texto de un documento web. No sólo se marca el contenido, sino además la meta-información que describe este contenido. Las páginas HTML se almacenan normalmente en el directorio raíz del servidor. Cómo se creó En la era digital, a los usuarios les resulta difícil hallar su camino en las webs y hacer un seguimiento de las estructuras de las plus para una solicitud de navegación. Normalmente deberían satisfacerse a través de la red, con 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:

Los archivos precargados se solicitan con la prioridad «más baja» y se almacenan en la caché HTTPEl HTTP (Hyper Text Transfer Protocol) es un protocolo que se usa para transmitir datos en redes. HTTP es un estándar técnico generalmente aceptado que establece cómo un cliente web se comunica con un servidor para que los datos solicitados por el cliente puedan ser cargados y mostrados. Información general Junto con el URL y el HTML, HTTP es uno de los conceptos más importantes de Internet (www). Fue desarrollado plus 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 browsersConcepto de Navegadores¿Qué son los Navegadores?Los Navegadores son herramientas informáticas que utilizamos para, normalmente, navegar por Internet y visitar cualquier página web, al mismo tiempo de para hacer otras tareas como ver documentos, observar vídeos o reproducir contenido multimedia de cualquier tipo. Son un tipo de software sencillamente usual y bastante utilizado hoy en día.Insistimos en que es algo que se utiliza con mucha frecuencia, puesto que moverse por Internet plus. 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 impressionsConcepto de Impresiones¿Qué son las Impresiones?Las Impresiones son las visiones o las veces que una publicación, link, texto, imagen o vídeo aparece frente a los ojos de un usuario. Si nos refiriéramos a Google y sus resultados, una impresión sería cada vez que una persona ve una de las webs que aparecen al realizar una búsqueda, sin ingresar siquiera en ella, tan solo viendo cómo aparece mientras baja con el plus 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¿Qué es un objetivo?En marketing, un objetivo es el resultado que se pretende alcanzar en un periodo de tiempo, a través el uso de los recursos disponibles. Por tanto, se debe formular de una forma clara y hace falta que sea accesible y medible. plus 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([
{urlEl URL (Localizador Uniforme de Recursos), es una dirección definida que apunta a la posición de un archivo en un servidor y lo recupera. Las URL se introducen en un navegador web para ingresar a documentos en la web o se incrustan como hipervínculos dentro de un documento. Se puede usar un Permalink para que una URL esté disponible de forma permanente. Componentes de una URL • prefijo de protocolo plus: '/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, JavaScriptJavaScript es un lenguaje de programación que funciona en el lado del cliente y con el que las webs pueden ser más funcionales. Incorporación en código HTML El código JavaScript puede ser incrustado en las páginas HTML, para que adquieran funcionalidad. Existen varias opciones. Puede estar entre las etiquetas <SCRIPT> y </SCRIPT>, puede estar contenido en un archivo externo, puede ser un parámetro de las etiquetas HTML, y puede estar plus, CSSConcepto de CSS¿Qué es el CSS?CSS es un lenguaje de programación que se usa para definir el estilo y el aspecto de un documento que se ha escrito mediante de un lenguaje de etiquetas, como HTML. Conocido además como hojas de estilo en cascada, es el que se emplea para dar colores, indicar tipos de letra o inclusive resaltar aspectos como el espacio entre items para dotar de estilo a plus, 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 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" 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.PluginConcepto de Plugin¿Qué es un Plugin?Un Plugin es un fragmento o componente de código hecho para ampliar las funciones de un programa o de una herramienta. En el ámbito del marketing digital, especialmente dentro del marketing de contenidos, es algo que se utiliza con mucha frecuencia dentro de entornos como WordPress, puesto que sirven al momento de contar con añadidos que hagan mucho más cómoda y completa la experiencia de plus({
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 etiquetas dinámicamente en la página, según una respuesta de la APIConcepto de API¿Qué es una API?Una API, siglas de Application Programming Interface o Interfaz de Programación de Apps, es un recopilatorio de código que se puede emplear para que varias apps se comuniquen entre ellas. Es algo que realiza una tarea equivalente a la interfaz de usuario al momento de promover la interacción entre persona y programa, solo que aplicado única y exclusivamente dentro del entorno del software.Aún cuando suene plus. 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') {
}
});




