Respond to browsing requests without waiting on the web using a service worker.
Network reliability
Las solicitudes de navegación son solicitudes de documentos HTML realizadas por su browser cada vez que ingresa una nueva Url en la barra de navegación o sigue un link en una página que lo lleva a una nueva URL. Aquí es donde los trabajadores del servicio tienen su mayor impacto en el rendimiento: si utiliza un trabajador del servicio para responder a las solicitudes de navegación sin esperar a la red, puede asegurarse de que las navegaciones sean rápidas y confiables, además de ser resistentes cuando la red no está disponible. Esta es la ganancia de rendimiento más grande que proviene de un trabajador de servicios, en comparación con lo que es posible con el almacenamiento en cache HTTP.
As detailed in the Identify Resources Loaded from the Network guide, a browse request is the first of many requests potentially made on the
"waterfall"
of traffic de la red. El HTML que carga a través de una solicitud de navegación inicia el flujo de todas las demás solicitudes de subrecursos como imágenes, scripts y estilos.
Inside a service worker fetch
event handler, you can determine if a request is a navigation by checking the request.mode
property in the FetchEvent
. If it is configured for 'navigate'
, then it is a navigation request.
As a general rule, do not 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
, para garantizar que el HTML, junto con la cadena de solicitudes de red posteriores, be (razonablemente) actualizado. Ir en contra de la red cada vez que el Username navega a una nueva página, lamentablemente significa que cada navegación might Be slow At the very least, it means it won't be surely Quick.
Cache-Control: no-cache
significa que el navegador debe verificar (o «revalidar») con el server antes de usar un recurso previamente almacenado en caché. Esto requiere que se complete una comunicación de red de ida y vuelta antes de que se pueda usar el recurso.
Different approaches to architectures
To find out as responder a las solicitudes de navegación evitando la red puede resultar complicado. El enfoque correcto depende en gran medida de la arquitectura de su sitio Web y de la cantidad de URL únicas a las que los usuarios pueden acceder.
While there is no one-size-fits-all solution, the following general guidelines should help you decide which approach is the most viable.
Small static sites
If your web application consists of a relatively small number (think: a couple dozen) of unique URLs, and each of those URLs corresponds to a different static HTML file, then a viable approach is to cache all of those HTML files and respond to navigation requests with the appropriate cached HTML.
With caching, you can cache the HTML in advance, as soon as the service worker is installed, and update the cached HTML each time you rebuild your site and redeploy your service worker.
Alternativamente, si prefiere evitar el almacenamiento en caché de todo su HTML, tal vez porque los usuarios tienden a navegar solo a un subconjunto de URL en su sitio, puede utilizar una strategy de almacenamiento en caché en tiempo de ejecución obsoleto mientras se revalida. Sin embargo, tenga cuidado con este enfoque, ya que cada documento HTML individual se almacena en caché y se actualiza por separado. El uso del almacenamiento en caché en tiempo de ejecución para HTML es más apropiado si tiene una pequeña cantidad de URL que se revisan frequently by the same set of users, and if you are comfortable with revalidating those URLs independently of each other.
Single page apps
Las aplicaciones web modernas utilizan con frecuencia una arquitectura de una sola página. En él, JavaScript del lado del client modifica el HTML en respuesta a las acciones del usuario. Este modelo utiliza el History API to modify the current URL as the user interacts with the web application, leading to what is effectively 'mock' browsing. While subsequent browsing may be "fake", the initial browsing is real and it is still important to ensure that it is not blocked on the web.
Fortunately, if you are using the single page architecture, there is a simple pattern to follow to serve the initial navigation from the cache: the application shell. In this model, your service worker responds to navigation requests by returning the same unique HTML file that has already been cached, regardless of the requested URL. This HTML should be basic and consist, perhaps, of a generic loading indicator or skeleton content. Una vez que el navegador ha cargado este HTML desde la caché, su JavaScript existente del lado del cliente toma el control y muestra el contents HTML correcto para la URL de la solicitud de navegación original.
Workbox provides the tools you need to implement this approach; the navigateFallback
option
allows you to specify which HTML document to use as your application's shell, along with an optional allow and deny list to limit this behavior to a subset of your URLs.
Multi-page apps
If your web server generates the HTML for your site dynamically, or you have more than a few dozen unique pages, then it is much more difficult to bypass the net when handling browsing requests. The advice in Everything Else likely applies to you.
But for a certain subset of multi-page applications, you might be able to implement a service worker that fully replicates the logic used on your web server to generate HTML. This works best if you can share routing information and templates between the server and service worker environments, and in particular if your web server uses JavaScript (without relying on
Node.js-specific features, such as file system access).
If your web server falls into that category and you would like to explore an approach to move HTML generation off the network to your service worker, the guide at Beyond SPAs: Alternative Architectures for Your PWA can help you get started.
Everything else
If you are unable to respond to cached HTML navigation requests, you should take steps to ensure that adding a service worker to your site (to handle other non-HTML requests) does not slow down your navigations. 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 Worker). You can mitigate this overhead by enabling a function called navigation preload, and then using network response
that has been preloaded within your fetch
event handler.
Workbox provides a helper library that function detects whether navigation preload is supported and, if so, simplifies the process of telling your service worker to use network response.
Photo by Aaron Burden in Unsplash,