服务工作者我们面临缓存问题

时间:2017-12-07 08:19:56

标签: caching service-worker offline-storage

我是服务工作者的新手。我正在尝试实现静态和动态缓存。

当我将单个文件添加到静态缓存请求时,它会获取我拥有的所有文件。目前,当我从离线模式启动时,所有文件都从服务工作者运行。请有人帮助我。

这是我在index.html中的代码。

       self.addEventListener('install',function(event)
      {
      console.log('[service worker]Installing service 
       worker....',event);
      event.waitUntil(caches.open('static')
      .then(function(cache)
      {
          console.log('[Service Worker] Precaching App Shell');
          cache.addAll([
                       '/',
                       '/signin.html',
                       ]); 
    })
  )
});

1 个答案:

答案 0 :(得分:0)

静态缓存中,某些请求(页面)被缓存(保存在浏览器的本地存储中),通常在服务工作者的install事件中完成。而在动态缓存页面&每当您请求(获取)它们时,都会缓存文件,因此,它会使用Service Worker的fetch事件。

因此,在install事件中,在'/'中添加cache.addAll时,服务工作者会添加显示'/'所需的所有文件和资源,即根目录。

现在,要使用这些缓存文件并实施动态缓存,您需要实现以下内容:

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

    event.respondWith(
      caches.match(event.request)       // if data has been cached already
        .then(function (response) {
          if (response) {
            return response;
          } else {              // else fetch from internet & cache in DYNAMIC cache
            return fetch(event.request)
              .then(function (res) {
                return caches.open(CACHE_DYNAMIC_NAME)
                  .then(function (cache) {
                    cache.put(event.request.url, res.clone());
                    return res;
                  })
              })
              .catch(function (err) {           //fallback mechanism
                return caches.open(CACHE_STATIC_NAME)
                  .then(function (cache) {
                    if (event.request.headers.get('accept').includes('text/html')) {
                      return cache.match('/offline.html');
                    }
                  });
              });
          }
        })
    );
});                  

注意:为避免过度拥挤本地存储,您可能希望在将文件保存到存储中之前实施一些策略。
有关详细信息,请阅读this以了解有关策略的更多信息。

相关问题