reactjscachingbrowser-cachecacheapi

Browser Cache Storage issue


I am storing 40,000 plus images in cache storage using cache.put(). I can see all the images in cache storage successfully stored. But when I am using my react js website offline, some images are displaying and some are not displaying. The browser decides itself to show an image or not. I am unable to find the reason. Can anyone help me?


Solution

  • I got a solution. Just we need an event listener in the Service worker. If there is GET request, it will first check-in the cache first and return from there

      self.addEventListener('fetch', event => {
      // Let the browser do its default thing
      // for non-GET requests.
      if (event.request.method !== 'GET') return;
      // Prevent the default, and handle the request ourselves.
      event.respondWith(async function() {
        // Try to get the response from a cache.
        const cache = await caches.open('images');
        const cachedResponse = await cache.match(event.request);
        if (cachedResponse) {
          // If we found a match in the cache, return it, but also
          // update the entry in the cache in the background.
          event.waitUntil(cache.add(event.request));
          return cachedResponse;
        }
        // If we didn't find a match in the cache, use the network.
        return fetch(event.request);
      }());
    });