我基于 current version 编写了一个简单的 PWA ( this tutorial)通过 Vaadin .它工作正常,在 Chrome 中测试过,也在离线模式下。
在移动设备上使用它会出现问题:
- 保存PWA后,启动一次,运行正常。
- 然后在关闭、打开飞行模式并重新启动 PWA 后,我收到一条系统消息,说我没有互联网连接 -> 没问题,我可以忽略它
- 忽略后,应用程序没有像我预期的那样加载静态 Assets ,而是显示一个空白页面,表示浏览器无法加载该页面,因为我没有互联网连接。
我认为 PWA 有什么用?为什么它不加载静态 Assets ?我认为我的 service-worker 很好:
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');
}
}
如果您认为问题出在其他地方,我很乐意分享更多代码!
最佳答案
我遇到了同样的问题。在我的例子中,问题来自于向 start_url 添加查询字符串的 list 。缓存对此很敏感。您可以向 .match 添加一个参数以防止它发生,如下所示:
caches.match(event.request, {ignoreSearch: true})
关于javascript - PWA 离线模式无法从移动浏览器的缓存中加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56171281/