簡體   English   中英

如何讓 Service Worker 緩存來自 API 的數據,並在需要時更新緩存

[英]How to make the Service Worker cache data from API and update the cache when needed

我將我的 React 應用程序轉換為 PWA,它部分工作正常。

我按照本教程進行操作: https://medium.com/@toricpope/transform-a-react-app-into-a-progressive-web-app-pwa-dea336bd96e6

然而這篇文章只展示了如何緩存 static 數據,我還需要存儲來自服務器的數據,我可以按照這篇文章的第一個答案的說明來做到這一點: 如何將數據從 API 緩存到 React PWA 中的緩存存儲? 並插入 firebase 地址,其中數據存儲到數組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);
          }
        })
      );
    })
  );
});

任何幫助將非常感激。

這聽起來像是你需要一個網絡優先策略,這在食譜中沒有提到。 此策略類似於網絡回退到緩存,但另外將響應始終存儲在緩存中。

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM