简体   繁体   English

Workbox Service Worker 不保存缓存

[英]Workbox Service Worker don't save cache

I implement a service Worker.我实现了一个服务工作者。 I looks pretty good, activating without errors, ...我看起来很不错,激活没有错误,...

But I cannot see something there:但我看不到那里的东西:

Service Worker 工作箱缓存

sw.min.js: 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'}
              })
            ]
          }));

This is in Google Chrome's Application -> Service Workers这是在Google Chrome's Application -> Service Workers

服务工作者工作箱

Try this code in your service worker:在您的服务人员中尝试此代码:

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;
      })
    })
  );
});

This approach is called stale-while-revalidate这种方法称为stale-while-revalidate

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

This means: If you fetch a page, i the service worker check if there is something in the cache and returns it from the cache to you, after returning it from the cache the service worker makes an request to the network and saves that request into the old cache.这意味着:如果你获取一个页面,我服务工作者检查缓存中是否有东西并将其从缓存中返回给你,在从缓存中返回它之后,服务工作者向网络发出请求并将该请求保存到旧缓存。

Next time you refresh you will see the updated version.下次刷新时,您将看到更新的版本。

On good approach is also: "cache with fallback to network"好的方法也是:“回退到网络的缓存”

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

This simply means: Take a look into the cache if there is something stored, if not then fetch it from the network.这只是意味着:如果有存储的东西,请查看缓存,如果没有,则从网络中获取它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM