Search code examples
javascriptcachingservice-workeroffline-caching

Javascript Service Worker use cache after network timeout


I have a web app which should work offline too. For this im using javascript service workers to put necessary files in the cache. If the connection is up, it loads all resources from the network. If there is no connection, the resources are loaded from the cache. This is working fine.

Now the problem is, if a have an internet connection on the device but the server is down. Then it never falls back to the cache because it has an internet connection.

Here is my code for the fetch event in the service-worker.js:

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

My idea is to implement a sort of timeout, if the application cant get the content in lets say 30 seconds then always use the cache. Does anyone have an idea how to implement this? Im not that fit with promises...


Solution

  • I guess your problem is that you're not opening an instance of the cache and then matching the request against that cache. You're using the caches API incorrectly.

    You need something like:

    return caches.open('my-cache-name').then...

    I highly suggest you to read through this: https://serviceworke.rs/strategy-network-or-cache.html

    There are lots of different SW strategies over at the same site!