我已经使用Create-React-App创建了SPA(单页应用程序)。我向其中添加了一个服务人员,以便在没有网络连接时可以加载SPA。服务工作者成功缓存所有资源,但在没有网络连接时无法响应。我已经尝试了很多事情,但是无法为资产提供服务来获得脱机功能。它给出以下错误信息:
未捕获(承诺中)TypeError:无法获取
我的服务工作者成功注册,也成功缓存了资产。服务人员代码:
const thingsToCache = [
'index.html',
'static/js/1.cb2fedf5.chunk.js',
'static/js/main.5e7fdc75.chunk.js',
'static/js/runtime~main.229c360f.js',
'static/css/main.ca6d346b.chunk.css',
'static/media/roboto.18d44f79.ttf',
'static/media/comfortaa.7d0400b7.ttf',
];
this.addEventListener('install', event => {
event.waitUntil(
caches.open('v1').then(cache => {
return cache.addAll(thingsToCache);
})
);
});
this.addEventListener('fetch', event => {
//respond to fetch requests here
caches
.match(event.request)
.then(cachedRes => {
if (cachedRes) {
event.respondWith(cachedRes);
} else {
throw new Error('No match found in cache!');
}
})
.catch(() => {
return fetch(event.request);
});
});
如果您需要资产,那么这里是链接:
https://github.com/Twaha-Rahman/pwa-problem-assets
感谢您的所有帮助!
fetch
事件侦听器中存在错误。您需要调用event.respondWith
而不是event.waitUntil
,并且它必须位于顶层。参见下面的修订版本。
this.addEventListener('fetch', event => {
event.respondWith(
caches
.match(event.request)
.then(cachedRes => {
if (cachedRes) {
return cachedRes;
} else {
throw new Error('No match found in cache!');
}
})
.catch(() => {
return fetch(event.request);
});
)
});
更多详细信息:https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers