[PWA] Cache JSON Data in a React PWA with Workbox, and Display it while Offline

We can view the PWA offline because we are caching the static and CDN assets for the app - but the list of todo items won't display, because those API calls are not being cached. We'll add another route to the service worker, to store the result of any .json API call from our server. Then, we'll be able to view the app with the entire list of items offline.

When we want to cache json file from our server:

workbox.skipWaiting();
workbox.clientsClaim();

workbox.routing.registerRoute(
    new RegExp('https:.*min.(css|js)'),
    workbox.strategies.staleWhileRevalidate({
        cacheName: 'cdn-cache'
    })
  )

// Cache the json files from our server
// for both production and dev '/'
  workbox.routing.registerRoute(
    new RegExp('/.*:4567.*.json'),
    workbox.strategies.networkFirst()
  )

workbox.precaching.precacheAndRoute(self.__precacheManifest || [])
原文地址:https://www.cnblogs.com/Answer1215/p/10192902.html