Use ServiceWorker cache only when offline Use ServiceWorker cache only when offline javascript javascript

Use ServiceWorker cache only when offline


Without testing this out, my guess is that you're not resolving respondWith() correctly in the case where there is no cache match. According to MDN, the code passed to respondWith() is supposed to "resolve by returning a Response or network error to Fetch." So why not try just doing this:

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


Why don't you open the cache for your fetch event?I think the process of a service worker is :

  • Open your cache

  • Check if the request match with an answer in your cache

  • Then you answer

OR (if the answer is not in the cache) :

  • Check the request via the network

  • Clone your answer from the network

  • Put the request and the clone of the answer in your cache for future use

I would write :

self.addEventListener('fetch', event => {  event.respondWith(    caches.open(CACHE_NAME).then(cache => {     return cache.match(event.request).then(response => {      return response || fetch(event.request)      .then(response => {        const responseClone = response.clone();        cache.put(event.request, responseClone);        })      })    } );});


event.respondWith() expects a promise that resolves to Response. So in case of a cache miss, you still need to return a Response, but above, you are returning nothing. I'd also try to use the cache first, then fetch, but in any case, as the last resort, you can always create a synthetic Response, for example something like this:

return new Response("Network error happened", {"status" : 408, "headers" : {"Content-Type" : "text/plain"}});