PWA offline mode not loading from cache on mobile browsers

巧了我就是萌 提交于 2019-12-13 04:27:20

问题


I wrote a simple PWA (current version) based on this tutorial by Vaadin. It works fine, tested in Chrome, also in offline mode.

By using it on a mobile device, issues occur:

  • After saving the PWA, starting it once, it runs fine.
  • then after closing, turning on flight mode and restarting the PWA, I get a system message, saying I have no internet connection -> no problem, I can ignore that
  • after ignoring, the app does not load the static assets as I expected it, but shows a blank page, saying the browser could not load the page, since I don't have internet connection.

I thought that is, what the PWA is good for? Why does it not load the static assets? I think my service-worker is just fine:

const staticAssets = [
    './',
    './styles.css',
    './app.js',
    './images',
    './fallback.json',
    './images/system/offline.png'
]



self.addEventListener('install', async event => {
    const cache = await caches.open('static-assets');
    cache.addAll(staticAssets);
});

self.addEventListener('fetch', event => {
    const req = event.request;
    const url = new URL(req.url);

    if(url.origin === location.origin){
        event.respondWith(cacheFirst(req));
    }else{
        event.respondWith(networkFirst(req));
    }

});


async function cacheFirst(req){
    const cachedResponse = await caches.match(req);
    return cachedResponse || fetch(req);
}

async function networkFirst(req){
    const cache = await caches.open('dynamic-content');
    try{
        const res = await fetch(req);
        cache.put(req, res.clone());
        return res;
    }catch(err){
        const cachedResponse = await cache.match(req);
        return cachedResponse || caches.match('./fallback.json');
    }
}

I'm happy to share more code, if you think the problem is somewhere else!


回答1:


The problem was within the service-worker:

I forgot to add the service worker file to the static assets.

Found the solution by reading the answers of this question: https://stackoverflow.com/a/44482764/7350000.



来源:https://stackoverflow.com/questions/56171281/pwa-offline-mode-not-loading-from-cache-on-mobile-browsers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!