2016-04-29 90 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