Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
December 27, 2020 09:54 pm GMT

PWA Caching Strategies

Caching strategies determine how a PWA behaves when the app makes a network request and how it deals with network failures. Workbox is a commonly used library for creating PWA; workbox-strategies provides the following caching strategies.

Stale-While-Revalidate

The service worker will serve the cached assets first, and update the cache with the latest version afterwards. On cache-hit, it responds to the request as quickly as possible. On cache-miss, the request falls back to network request. The response from network request is then used to update the cache. This strategy is useful in situation where receiving a response has higher priority over having most up-to-date results.

Cache First

The service worker will serve the cached assets and will only query the network if the cache is not available. On cache-hit, it will not update the cache in background; the network will not be used at all. On cache-miss, the request will be sent over the network and the response will be cached. The next request will then be served from the cache. This strategy is useful for requests for static assets, which do not change frequently.

If no caching strategy is defined, Workbox will use Cache First as default.

Network First

The service worker will by default try to fetch the response over the network. If the network request fails, it will serve the response from the cache. On successful response over the network, it will cache the response for future use. This strategy can be useful in requests that update frequently.

Network Only

The service worker will always query the network for response. This can be useful if you require to query the network strictly.

Cache only

The service worker will always query the cache for response. You need to make sure that you pre-cache resources before requesting. This strategy is less used in practice.

Example Usage

On your service-worker.ts, add a custom strategy for a fetch event.
Note: You could also define custom events for different fetch requests by filtering depending on URL origin or path.

import { StaleWhileRevalidate } from "workbox-strategies";...//! Stale-While-Revalidate for all fetch eventsself.addEventListener("fetch", (event) => {    const { request } = event;    event.respondWith(new StaleWhileRevalidate().handle({ event, request }));});
Enter fullscreen mode Exit fullscreen mode

Workbox also allows you to define custom strategies. All of these strategies also allow you to configure name of cache, cache expiration and an array of additional workbox plugins.

Happy Hacking!


Original Link: https://dev.to/pssingh21/pwa-caching-strategies-1d7c

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To