Service Worker 和透明缓存更新

Service Worker and transparent cache updates

我正在尝试为一个简单但古老的 Django Web 应用程序安装 ServiceWorker。我开始使用示例 read-through caching example from the Chrome team

这很好用但并不理想,因为我想在需要时更新缓存。根据此处阅读所有其他服务工作者的回答,有两种推荐的方法可以做到这一点。

  1. 使用一些服务器端逻辑来了解您显示的内容何时更新,然后更新您的服务人员以更改预缓存的内容。例如,这就是 sw-precache 所做的。

  2. 每当您依赖更新的资源时,只需更新 service worker JS 文件中的缓存版本(参见上面缓存示例中 JS 文件中的注释)。

对我来说都不是很好的解决方案。首先,这是一个愚蠢的遗留应用程序。我没有 sw-precache 依赖的应用程序堆栈。其次,其他人更新将要显示的数据(它基本上是带有详细信息页面的事物列表)。

我想尝试 Jake Archibald 在他的 offline cookbook 中建议的 "use cache, but update the cache from network",但我无法完全实现它。

我最初的想法是我应该能够 return 我的 service worker 中的缓存版本,但是如果网络可用则将更新缓存的函数排队。例如,在 fetch 事件监听器中有这样的东西

// If there is an entry in cache, return it after queueing an update
console.log(' Found response in cache:', response);
setTimeout(function(request, cache){
    fetch(request).then(function(response){
        if (response.status < 400 && response.type == 'basic') {
            console.log("putting a new response into cache");
            cache.put(request, response);
        }   
    })  
},10, request.clone(), cache);

return response;

但这不起作用。页面卡在加载中。

上面的代码有什么问题?实现我的目标设计的正确方法是什么?

听起来 https://jakearchibald.com/2014/offline-cookbook/#stale-while-revalidate 与您要查找的内容非常接近

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) {
          // if we got a response from the cache, update the cache
          if (response) {
            cache.put(event.request, networkResponse.clone());
          }
          return networkResponse;
        });

        // respond from the cache, or the network
        return response || fetchPromise;
      });
    })
  );
});

在页面重新加载时,您可以使用新版本刷新您的服务人员,同时旧版本将处理请求。

一旦一切都完成并且没有页面使用旧的 service worker,它将使用更新版本的 service worker。

this.addEventListener('fetch', function(event){
    event.responseWith(
        caches.match(event.request).then(function(response){
            return response || fetch(event.request).then(function(resp){
                return caches.open('v1').then(function(cache){
                    cache.put(event.request, resp.clone());
                    return resp;
                })
            }).catch(function() {
                return caches.match('/sw/images/myLittleVader.jpg');
            });
        })
    )
});

我建议您浏览下面 link 以了解详细功能

https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers