MHadi Taghdisi
MHadi Taghdisi

Reputation: 460

why service worker cache all images?

I'm just testing service worker features to know how it works. so now I've faced a problem.

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);
        }
      )
    );
  });

these are the codes i used to cache just two images but apparently service worker cashe all images,and some css and javascripts(i checked disable cache in network tab) below image shows all images in img folder are called by service worker. enter image description here

I checked cache storage too and as you can see there are just two images and image folder too!! I'm confused!! Would be super helpful if someone could provide some clarification of this. enter image description here

Upvotes: 3

Views: 2416

Answers (1)

Jiayi Hu
Jiayi Hu

Reputation: 2270

A bit later in the answer, but since you are intercepting all the fetch requests, even not cached images are returned by the service worker because of this line:

return fetch(event.request)

The label (from ServiceWorker) just means that it has been returned by a Service Worker, for both when from the cache or the network.

Upvotes: 1

Related Questions