Search code examples
javascriptweb-applicationsservice-workeroffline

ServiceWorker Cache Behaviour Inconsistent Depending On Device And Installation Status


When using the service worker below, the behaviour is inkonsistent accross devices - unfortunately, just one of them is desired so far...

  1. When I load the website in a normal browser tab (not via installed app) and simulate offline in the Chrome DevTools it actually loads everything from cache as excepted (html, css, js) and looks like this:

enter image description here

  1. On a PC, when I launch the installed web app, simulate offline mode and reload the page, I see the following:

enter image description here

  1. When I do the same on a mobile device and launch the installed web app the second time offline, it loads the HTML only without css/js.

How can I fix my service worker such that the outcome is always like in the first case?

self.addEventListener('fetch', event => {
    if(event.request.method !== 'GET')
        return;

    function versionedURL(request){
        switch(request.destination){
            case 'image':
            case 'script':
            case 'style':
                let
                    version = self.serviceWorker.scriptURL.split('?')[1]
                ;
                return new Request(request.url + '?' + version);
            
            default:
                return request;
        }
    }

    let
        request = event.request.url.startsWith('https://matchflix.ch/') ? versionedURL(event.request) : event.request
    ;
    event.respondWith(caches.open('matchflix')
        .then(cache => fetch(request)
            .then(response => {
                cache.put(request, response.clone());
                return response;
            })
            .catch(() => cache.match(request))
        )
    );
});


Solution

  • There was a mixup with the www and non-www version. After redirecting everything to the non-www version, it works now properly on every device.