1

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...

1 Answer 1

2

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!

Sign up to request clarification or add additional context in comments.

1 Comment

thx for the link! this sounds promising, i will test it in the next year ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.