Warm tip: This article is reproduced from stackoverflow.com, please click
browser-cache caching javascript service-worker

Service Workers

发布于 2020-05-03 06:58:50

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?

Questioner
Plastic
Viewed
39
failedCoder 2020-02-14 20:50

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