The Current code looks like does Cache first Strategy, How to modify it use Network first and than fallback to cache if network fails ?

async function onFetch(event) {
    let cachedResponse = null;
    if (event.request.method === 'GET') {
        // For all navigation requests, try to serve index.html from cache
        // If you need some URLs to be server-rendered, edit the following check to exclude those URLs
        //const shouldServeIndexHtml = event.request.mode === 'navigate';

        console.log("onFetch : " + event.request.url.toLowerCase());

        const shouldServeIndexHtml = event.request.mode === 'navigate';
           

        const request = shouldServeIndexHtml ? 'index.html' : event.request;
        const cache = await caches.open(cacheName);
        cachedResponse = await cache.match(request);
    }

    return cachedResponse || fetch(event.request);
}
1

There are 1 best solutions below

0
On
if (event.request.url.indexOf('/api') != -1) {
    try {
        // Network first
        var response = await fetch(event.request);
        // Update or add cache
        await cache.put(event.request, response.clone());
        // Change return value
        cachedResponse = response;
    }
    catch (e)
    {
                
    }
}

You can add something like this after:

cachedResponse = await cache.match(request);

This should always load api requests from the network first, since it's not part of the cache initially. Every time the cache is renewed for this request. If the request fails, the cached value will be used.