如何让 Service Worker 缓存来自 API 的数据并在需要时更新缓存

Ber*_*den 6 javascript reactjs service-worker progressive-web-apps

我将 React 应用程序转换为 PWA,并且部分工作正常。

我遵循了本教程:https://medium.com/@toricpope/transform-a-react-app-into-a-progressive-web-app-pwa-dea336bd96e6

然而,本文仅展示如何缓存静态数据,我还需要存储来自服务器的数据,我可以按照本文第一个答案的说明执行此操作:How can I cache data from API to Cache Storage in React PWA ?并将存储数据的 firebase 地址插入到 array 中urlsToCache,并由应存储到缓存中的文件填充。

到目前为止一切都很好,但是在将数据存储到缓存中之后,应用程序将停止从服务器获取数据并仅使用缓存中的数据加载页面,即使服务器已更新也是如此。这就是我需要解决的问题。

简而言之,我需要从服务器获取数据,将其存储到缓存中,以便在应用程序离线时使用它,并在每次到达服务器时更新缓存。

我正在尝试遵循本指南,但没有成功:https://developers.google.com/web/fundamentals/instant-and-offline/offline-cookbook/#serving-suggestions

这是我的worker.js 文件:

var CACHE_NAME = 'pwa-task-manager';
var urlsToCache = [
  '/',
  '/completed',
  '/index.html',
  '/static/js/main.chunk.js',
  '/static/js/0.chunk.js',
  '/static/js/1.chunk.js',
  '/static/js/bundle.js',
  '/calculadora',
  'https://calc-marmo.firebaseio.com/clientes.json',
  'https://calc-marmo.firebaseio.com/adm.json',
];

// Install a service worker
self.addEventListener('install', event => {
  // Perform install steps
  event.waitUntil(
    caches.open(CACHE_NAME)
      .then(function(cache) {
        console.log('Opened cache');
        return cache.addAll(urlsToCache);
      })
  );
});

// Cache and return requests
self.addEventListener('fetch', event => {
  event.respondWith(
    caches.match(event.request)
      .then(function(response) {
        // Cache hit - return response
        if (response) {
          return response;
        }
        return fetch(event.request);
      }
    )
  );
});

// Update a service worker
self.addEventListener('activate', event => {
  var cacheWhitelist = ['pwa-task-manager'];
  event.waitUntil(
    caches.keys().then(cacheNames => {
      return Promise.all(
        cacheNames.map(cacheName => {
          if (cacheWhitelist.indexOf(cacheName) === -1) {
            return caches.delete(cacheName);
          }
        })
      );
    })
  );
});
Run Code Online (Sandbox Code Playgroud)

任何帮助将非常感激。

Ste*_*ser 7

这听起来像是您需要一个网络优先策略,但食谱中没有提及。此策略类似于网络回退到缓存,但另外始终将响应存储在缓存中。

说明: https: //developers.google.com/web/tools/workbox/modules/workbox-strategies#network_first_network_falling_back_to_cache

代码示例(如果您不使用工作箱):https://gist.github.com/JMPerez/8ca8d5ffcc0cc45a8b4e1c279efd8a94