簡體   English   中英

Workbox Service Worker 不保存緩存

[英]Workbox Service Worker don't save cache

我實現了一個服務工作者。 我看起來很不錯,激活沒有錯誤,...

但我看不到那里的東西:

Service Worker 工作箱緩存

sw.min.js:

workbox.routing.registerRoute(
          ({request}) => request.destination === 'style',
          new workbox.strategies.NetworkFirst({
           // cacheName: cacheNamecss,
            plugins: [
              new workbox.expiration.ExpirationPlugin({
                maxEntries: 20,
                maxAgeSeconds: 7 * 24 * 60 * 60
              }),
              new workbox.cacheableResponse.CacheableResponsePlugin({
                statuses: [0, 200],
                headers: {'X-Is-Cacheable': 'yes'}
              })
            ]
          }));

這是在Google Chrome's Application -> Service Workers

服務工作者工作箱

在您的服務人員中嘗試此代碼:

self.addEventListener('fetch', function(event) {
  event.respondWith(
    caches.open('mysite-dynamic').then(function(cache) {
      return cache.match(event.request).then(function(response) {
        var fetchPromise = fetch(event.request).then(function(networkResponse) {
          cache.put(event.request, networkResponse.clone());
          return networkResponse;
        })
        return response || fetchPromise;
      })
    })
  );
});

這種方法稱為stale-while-revalidate

https://developers.google.com/web/fundamentals/instant-and-offline/offline-cookbook#stale-while-revalidate

這意味着:如果你獲取一個頁面,我服務工作者檢查緩存中是否有東西並將其從緩存中返回給你,在從緩存中返回它之后,服務工作者向網絡發出請求並將該請求保存到舊緩存。

下次刷新時,您將看到更新的版本。

好的方法也是:“回退到網絡的緩存”

self.addEventListener('fetch', function(event) {
  event.respondWith(
    caches.match(event.request).then(function(response) {
      return response || fetch(event.request);
    })
  );
});

這只是意味着:如果有存儲的東西,請查看緩存,如果沒有,則從網絡中獲取它。

暫無
暫無

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

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