为什么Service Worker要缓存所有图片?

3

我只是在测试服务工作线程功能,以了解它的工作原理。所以现在我遇到了一个问题。

var CACHE_NAME = 'my-site-cache-v1';
var urlsToCache = [    
  '/img/map.jpg', 
  '/img/chicago.jpg',  
];

self.addEventListener('install', function(event) {
    // Perform install steps
    event.waitUntil(
      caches.open(CACHE_NAME)
        .then(function(cache) {
          console.log('Opened cache');
          return cache.addAll(urlsToCache);
        })
    );
  });

  self.addEventListener('fetch', function(event) {
    event.respondWith(
      caches.match(event.request)
        .then(function(response) {
          // Cache hit - return response
          if (response) {
            return response;
          }
          return fetch(event.request);
        }
      )
    );
  });

这是我用来缓存仅两个图像的代码,但显然服务工作者会缓存所有图像、一些 CSS 和 JavaScript(我在网络选项卡中检查了禁用缓存)。下面的图像显示服务工作者调用了 img 文件夹中的所有图像。 输入图像描述 我也检查了缓存存储,正如你所看到的,只有两张图片和图像文件夹!!我很困惑!!如果有人能提供一些澄清解释,那将非常有帮助。 输入图像描述
1个回答

1
稍晚些在答案中解释,但由于您拦截了所有的获取请求,即使未被缓存的图像也会被服务工作者返回,因为有这行代码:
return fetch(event.request)
表示该标签是由 Service Worker 返回的,无论是从缓存还是网络返回。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接