2016-04-29 95 views
0

我的服務員有問題。我已經使用Cache和Network技術實現了它,其中內容首先從緩存中獲取,並且始終執行網絡獲取並且成功緩存結果。 (受此解決方案的啓發,CSS-Tricks服務人員,雙緩存?

當我更改我的web應用程序並點擊刷新時,我當然會第一次獲取舊內容。但在隨後的刷新中,內容會在新舊之間交替出現。我可以連續五次獲取新內容或舊內容,或者每次請求可能會有所不同。

我一直在調試服務人員一段時間,並沒有得到任何明智的。有沒有人有關於執行有什麼問題的想法?

編輯:

var version = 'v1::2'; 

self.addEventListener("install", function (event) { 
    event.waitUntil(
     caches 
     .open(version + 'fundamentals') 
     .then(function (cache) { 
      return cache.addAll([ 
       "/" 
      ]); 
     }) 
    ); 
}); 

self.addEventListener("fetch", function (event) { 

    if (event.request.method !== 'GET') { 
     return; 
    } 
    event.respondWith(
     caches 
     .match(event.request) 
     .then(function (cached) { 
      var networked = fetch(event.request) 
       .then(fetchedFromNetwork, unableToResolve) 
       .catch(unableToResolve); 

      return cached || networked; 

      function fetchedFromNetwork(response) { 
       var cacheCopy = response.clone(); 

       caches 
        .open(version + 'pages') 
        .then(function add(cache) { 
         cache.put(event.request, cacheCopy); 
        }); 

       return response; 
      } 

      function unableToResolve() { 

       return new Response('<h1>Service Unavailable</h1>', { 
        status: 503, 
        statusText: 'Service Unavailable', 
        headers: new Headers({ 
         'Content-Type': 'text/html' 
        }) 
       }); 
      } 
     }) 
    ); 
}); 

self.addEventListener("activate", function (event) { 

    event.waitUntil(
     caches 
     .keys() 
     .then(function (keys) { 
      return Promise.all(
       keys 
       .filter(function (key) { 
        return !key.startsWith(version); 
       }) 
       .map(function (key) { 
        return caches.delete(key); 
       }) 
      ); 
     }) 
    ); 
}); 
+0

我想你需要做更多的挖掘才能找出究竟發生了什麼。您可以在隱身窗口或隱私瀏覽模式下重現此行爲嗎?使用調試工具,你能看到服務人員的請求嗎? – mjs

+0

這是可能的,但不可能的網絡代碼後的緩存不完成,但pelase,粘貼你的具體代碼,讓我們看看。 – Salva

+0

更新了代碼 – robbannn

回答

0

我不知道你是如何設置的版本,但我相信多個緩存仍然存在(我可以看到你正在試圖刪除以前的緩存,但仍然)。 caches.match() is a convenience method和順序不保證(至少鉻似乎查詢最早的第一)。 Chrome開發人員工具向您顯示現有緩存(應用程序/緩存/緩存存儲)及其內容。如果您想查詢特定的緩存,你需要做的:

caches.open(currentCacheName).then(function(cache) {...} 

in the example in the Cache documentation

+0

我知道這個問題很老,但我首先遇到了同樣的案例頭,並認爲答案可能會幫助其他人來解答這個問題 – Kalle