history.pushState()在刷新时阻止“安装”中的Service Worker

时间:2017-03-17 14:54:22

标签: javascript caching service-worker

我有一个相当简单的服务工作者(见下面的代码),我遇到了以下问题:

每次刷新时,浏览器都会尝试安装新的服务工作者(即使服务工作者和我的缓存资源没有变化)。在我的网站首次刷新后,这会使我的服务工作者在一个持续的“安装”阶段被阻止(参见Screenshot)。如果我使用skipWaiting(),则会独立发生。

其他一切看起来很好:注册时没有错误消息,所有资源都可以在“缓存存储”等中找到。

编辑:所以我发现在我们的应用程序初始化时调用history.pushState()会阻止我的服务工作者处于“安装”状态。如果我在没有此调用或使用setTimeout()的情况下运行应用程序,则服务工作者可以正常运行。这给我的印象是,在服务工作者注册之前调用history.pushState()会使工作块阻塞。有什么想法吗?

var version = 1489760334594;
var CACHE_NAME = 'mini-cache-v' + version;

var urlsToCache = ['./index.html','./app.css','./app.js','./assets/layers-2x.png','./assets/layers.png','./assets/logo-x48.png','./assets/logo.png','./assets/marker-icon.png','./assets/marker-shadow.png','./assets/poi.png','./assets/status.png','./assets/MaterialIcons-Regular.eot','./assets/MaterialIcons-Regular.ttf','./assets/roboto-regular.ttf','./assets/MaterialIcons-Regular.woff','./assets/MaterialIcons-Regular.woff2'];


self.addEventListener('install', function (event) {
  console.log('INSTALL SW: ', CACHE_NAME);
  //Open cache and add new resources from network
  event.waitUntil(
    caches.open(CACHE_NAME)
      .then(function (cache) {
        console.log('Opened cache');
        return cache.addAll(urlsToCache)
          .then(function(){
            console.log('Added resources');        
          })
      })  
  );
  //Activate new SW directly
  // console.log('SKIP WAITING');
  // return self.skipWaiting();
});

self.addEventListener('activate', function(event) {
  console.log('ACTIVATE SW: ', CACHE_NAME);
  //Delete old caches
  event.waitUntil(
    caches.keys().then(function(keyList) {
      return Promise.all(keyList.map(function(key) {
        if (key !== CACHE_NAME) {
          return caches.delete(key);
        }
      }));
    }) 
  );
});

self.addEventListener('fetch', function(event) {
  //If present serve from cache, else from network
  event.respondWith(
    caches.open(CACHE_NAME).then(function(cache){
      return cache.match(event.request.url)
        .then(function(response) {
          if (response) {
            console.log('SERVED FROM CACHE:', response);
            return response;
          }
          return fetch(event.request).then(function(response){
              // console.log('Response from network is:', response);
              return response;
          });
        }
      )
    })
  );
});

0 个答案:

没有答案
相关问题