Skip to content
Advertisement

Service Workers – selectively choose resources

I have a simple Service Worker implementation like this:

var CACHE_NAME = "app-cache-v1";
var urlsToCache = ["./style/main.css", "./app.ts.js"];

self.addEventListener("install", function(event) {
    event.waitUntil(
        caches.open(CACHE_NAME).then(function(cache) {
            return cache.addAll(urlsToCache);
        })
    );
});
self.addEventListener("activate", function(event) {
    event.waitUntil(
        caches.keys().then(function(cacheNames) {
            return Promise.all(
                cacheNames.map(function(cacheName) {
                    return caches.delete(cacheName);
                })
            );
        })
    );
});

self.addEventListener("fetch", function(event) {
    event.respondWith(
        fetch(event.request).catch(function() {
            return caches.match(event.request);
        })
    );
});

My goal is to cache all resources except the two files indicated in the urlsToCache variable, these two files should ALWAYS be requested from the network.. How can i achieve this? How can I then verify that it is actually so?

Advertisement

Answer

You can check the url of the request in fetch event handler before deciding what caching strategy to use:

self.addEventListener("fetch", function(event) {
  const url = new URL(event.request.clone().url);
  if (urlsToCache.indexOf(url.pathname) !== -1) { // check if current url exists in your array
     event.respondWith(
         // without cacheing
     );
  } else {
     event.respondWith(
        // with cacheing
     );
  }
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement