2017-04-15 19 views
1

我有一些按预期工作的服务人员,主要是根据指示获取,缓存和请求内容。如何停止添加未在服务工作者声明的内容,同时在域名下导航

但是我注意到,除了指定的内容,比如在服务工作者中声明的文件/文件夹,未声明的内容被添加到缓存中,同时在域中导航。

顺便说一下,这是一个问题,它膨胀了缓存空间,并且通常我不希望它被缓存。

在域下导航时,如何通过Service Worker内容添加非声明内容?

这是th SW的安装代码,它负责添加内容。

// Declaring cache name, version, files to be cached. 
self.addEventListener('install', function(e) { 
    console.log('[ServiceWorker] Install'); 
    e.waitUntil(
    caches.open(CACHE_NAME).then(function(cache) { 
      console.log('[ServiceWorker] DTL Install Caching App Shell'); 
      return Promise.all([cache.addAll(FILES_TO_CACHE)]); 
     }).then(function() { 
      //skiWaiting, forza instalacion de SW. 
      return self.skipWaiting(); 
     }) 
); 
}); 

虽然导航到该域的其他文件夹,但内容将要缓存阵列中没有声明,像往常一样取指事件被触发,该代码是这样的:

self.addEventListener('fetch', function(event) { 
console.log('SW DTL fetch');                                        
    event.respondWith(
    caches.open(CACHE_NAME).then(function(cache) { 
     return fetch(event.request).then(function(response) { 
      cache.put(event.request, response.clone()); 
      return response; 
     }); 
     }) 
);  
}); 

回答

4

您不必阻止任何事情,因为Service Worker默认不会自动将项目添加到缓存。实际上,您正在使用Cache.put()方法在fetch处理程序中手动将项目添加到缓存

你应该使用的是Cache.match()而不是;

event.respondWith(
    caches.match(event.request).then(function (response) { 
     // return the response if it is found in cache 
     if (response) return response; 

     // fall back to network as usual otherwise 
     console.log('SW: No response found in cache. About to fetch from network...'); 
     return fetch(event.request).then(function (response) { 
      return response; 
     }); 
    }) 
); 
相关问题