【问题标题】:PWA offline mode not loading from cache on mobile browsersPWA 离线模式无法从移动浏览器的缓存中加载
【发布时间】:2019-10-03 21:25:41
【问题描述】:

我基于this tutorial by Vaadin 编写了一个简单的 PWA (current version)。它工作正常,在 Chrome 中测试过,也在离线模式下。

在移动设备上使用它会出现问题:

  • 保存 PWA 后,启动一次,运行正常。
  • 然后关闭,打开飞行模式并重新启动 PWA 后,我收到一条系统消息,说我没有互联网连接 -> 没问题,我可以忽略它
  • 忽略后,应用程序没有像我预期的那样加载静态资产,而是显示一个空白页面,说浏览器无法加载该页面,因为我没有互联网连接。

我想,PWA 有什么用?为什么它不加载静态资产?我认为我的服务人员很好:

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');
    }
}

如果您认为问题出在其他地方,我很乐意分享更多代码!

【问题讨论】:

  • 并没有真正回答您的逻辑有什么问题,但我个人通过使用 google 的 Workbox 在离线 PWA 方面取得了成功。无需重新发明他们已经开发的轮子,您可以使用他们已经开发的脚手架,而只需担心编写与您的应用程序实际相关的代码。
  • “空白页”是否是带有“请检查您的互联网连接并重试”的页面。`(所以是您自己编码的那个?)
  • 不,不在我的设备上。我看到标准的 Safari 空白页(“Safari 无法打开页面 [...]”)。你得到我在移动设备上编码的那个了吗?!我只在 Mac 版 Chrome 上得到了这个。

标签: javascript caching service-worker progressive-web-apps offline-mode


【解决方案1】:

我遇到了同样的问题。在我的例子中,问题来自于向 start_url 添加查询字符串的清单。缓存对此很敏感。您可以向 .match 添加一个参数以防止它发生,如下所示:

caches.match(event.request, {ignoreSearch: true})

【讨论】:

    【解决方案2】:

    问题出在服务人员内部:

    我忘记将 service worker 文件添加到静态资产中。

    通过阅读以下问题的答案找到了解决方案:https://stackoverflow.com/a/44482764/7350000

    【讨论】:

      猜你喜欢
      • 2016-10-06
      • 1970-01-01
      • 2023-03-03
      • 1970-01-01
      • 2018-07-25
      • 2019-09-30
      • 1970-01-01
      • 2021-08-26
      • 1970-01-01
      相关资源
      最近更新 更多