2015-11-08 43 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