【发布时间】:2020-12-15 12:37:31
【问题描述】:
在我的网络应用程序中,我创建了一个离线 html 页面,并编写了一个服务工作者,比如如果网络中断,它应该为所有请求返回离线页面。这样,如果在离线状态下触发任何请求,Service Worker 将返回离线 html 页面作为响应。但离线 html 未显示在页面中。如果我刷新页面离线 html 页面。这是因为在刷新页面时获取原始 html 页面时,sw 发现 notwork 不存在,因此它正在返回离线页面。
self.addEventListener('fetch', (event) => {
event.respondWith((async () => {
try {
const networkResponse = await fetch(event.request);
return networkResponse;
} catch (error) {
console.log('Fetch failed; returning offline page instead.', error);
const cache = await caches.open(CACHE_NAME);
const cachedResponse = await cache.match(OFFLINE_URL);
return cachedResponse;
}
})());
})
有什么方法可以在不刷新页面的情况下显示离线页面。也就是说,一旦我离线并触发任何请求,我想删除旧的 html 页面并显示离线页面。
【问题讨论】:
-
您能否分享您的 fetch 事件处理程序代码以显示离线页面功能?