问题描述
我写了一个简单的PWA(当前版本获取新闻)在本教程上,由 Vaadin .在Chrome浏览器中进行了测试,也可以在离线模式下正常运行.
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:
- 保存PWA后,将其启动一次,即可正常运行.
- 然后在关闭,打开飞行模式并重新启动PWA之后,我收到系统消息,说我没有互联网连接->没问题,我可以忽略
- 忽略后,该应用程序未按预期加载静态资产,但显示空白页面,表示浏览器无法加载该页面,因为我没有互联网连接.
我认为PWA有什么用?为什么不加载静态资产?我认为我的服务人员很好:
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!
推荐答案
问题出在服务人员内部:
The problem was within the service-worker:
我忘记了将服务工作者文件添加到静态资产中.
I forgot to add the service worker file to the static assets.
通过阅读以下问题的答案来找到解决方案: https://stackoverflow.com/a/44482764/7350000.
Found the solution by reading the answers of this question: https://stackoverflow.com/a/44482764/7350000.
这篇关于PWA脱机模式无法从移动浏览器的缓存中加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!