Sameera Thilakasiri
Sameera Thilakasiri

Reputation: 9508

Caching only images inside of a service worker

Following is the code for the SW, all working fine. I was caching all the dynamic pages previously, but this was creating me some issues. Like page DOM changes after users interaction are not reflected next time page view. Always it shows original DOM.

SO I have needed the only image caching dynamically. I have commented original code which was caching all content.

self.addEventListener('activate', function(event) {
  console.log('[Service Worker] Activating Service Worker ....', event);
  /*event.waitUntil(
    caches.keys()
      .then(function(keyList) {
        return Promise.all(keyList.map(function(key) {
          if (key !== CACHE_STATIC_NAME && key !== CACHE_DYNAMIC_NAME) {
            console.log('[Service Worker] Removing old cache.', key);
            return caches.delete(key);
          }
        }));
      })
  );*/
  return self.clients.claim();
});

self.addEventListener('fetch', function(event) {
  event.respondWith(
    caches.match(event.request)
      .then(function(response) {
        if (response) {
          return response;
        } else {
          /*return fetch(event.request)
            .then(function(res) {
              return caches.open(CACHE_DYNAMIC_NAME)
                .then(function(cache) {

                    /!*if ( event.request.url.indexOf( 'maps.google' ) !== -1 ) {
                        return false;
                    }*!/
                    if (!/^https?:$/i.test(new URL(event.request.url).protocol)) {
                        return;
                    }

                    cache.put(event.request.url, res.clone());
                    return res;
                })
            })
            .catch(function(err) {

                console.log('show offline page as cashe and network not available')
                return caches.open(CACHE_STATIC_NAME)
                    .then(function (cache) {
                        return cache.match(OFFLINE_URL);
                    });
            });*/

            return fetch(event.request);
        }
      })
  );
});

Upvotes: 0

Views: 7957

Answers (1)

Jeff Posnick
Jeff Posnick

Reputation: 56044

I'd recommend following the approach outlined in this "Service Worker Caching Strategies Based on Request Types" article, and use request.destination inside of your fetch handler to figure out which requests are going to be used for images.

self.addEventListener('fetch', (event) => {
  if (event.request.destination === 'image') {
    event.respondWith(/* your caching logic here */);
  }

  // If you don't call event.respondWith() for some requests,
  // the normal loading behavior will be used by default.
};

It's possible that a request for an image might be loaded via something like XMLHttpRequest, in which case the request.destination value likely won't be set properly. If that's the case, I'd recommend just checking the portion of the URL you feel is most likely to be unique using string comparisons.

self.addEventListener('fetch', (event) => {
  const url = new URL(event.request.url);
  if (url.origin.includes('maps.google')) {
    event.respondWith(/* your caching logic here */);
  }

  // If you don't call event.respondWith() for some requests,
  // the normal loading behavior will be used by default.
};

Upvotes: 3

Related Questions