-1

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

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

这是我在 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',
                       ]); 
    })
  )
});
4

1 回答 1

0

静态缓存中,一些请求(页面)被缓存(保存在浏览器的本地存储中),通常在installService Worker 的情况下完成。而在动态缓存页面和文件中,只要您请求(获取)它们就会被缓存,因此它利用fetch了 Service Worker 的事件。

因此,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');
                    }
                  });
              });
          }
        })
    );
});                  

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

于 2017-12-07T09:01:11.110 回答