2015-11-08 25 views
2

我正在尝试为简单但旧的Django Web应用程序安装ServiceWorker。我开始使用示例read-through caching example from the Chrome team服务工作者和透明缓存更新

这很好,但并不理想,因为我想更新缓存(如果需要)。有两种建议的方法可以在阅读所有其他服务人员答案的基础上做到这一点。

  1. 使用一些服务器端逻辑,知道什么时候告诉你的东西已经更新,然后更新您的服务人员来改变什么是预缓存。例如,这是sw-precache所做的。

  2. 无论何时您依赖更新的资源,只需更新服务工作者JS文件中的缓存版本(请参阅上述缓存示例中的JS文件中的注释)。

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

我想尝试一下Jake Archibald在他的offline cookbook中建议的“使用缓存,但更新网络缓存”,但我无法完成它的工作。

我原来的想法是我应该能够返回缓存版本在我的服务工作者,但排队功能,如果网络可用更新缓存。例如,在提取事件监听器中,类似这样的东西

// 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; 

但是这不起作用。该页面卡住加载。

上面的代码有什么问题?什么是正确的方式来达到我的目标设计?

回答

4

这听起来像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; 
     }); 
    }) 
); 
}); 
+0

嗯..不大,因为,如果我没看错,这仍然会先打网络。因此,对于速度较慢的网络,它需要很长时间,然后返回网络响应(很可能与缓存的响应相同)。这将脱机,但速度不快。 – devd

+0

不,缓存响应不会等待网络请求,所以如果缓存 –

+0

aah即可获得即时响应。所以如果响应为空,那么fetchPromise会解析? – devd

0

在重新加载页面,你可以刷新与新版本同时旧的将采取的要求照顾你的服务人员。

一旦一切完成,并且没有页面正在使用旧的服务工作者,它将使用更新版本的服务工作者。

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

我建议你走过下面的链接了解详细的功能

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