我有一个服务工作者应该缓存一个offline.html
客户端没有网络连接时显示的页面。然而,有时它会认为导航器已离线,即使它并未离线。那是,navigator.onLine === false
。这意味着用户可能会得到offline.html
而不是实际内容,即使在线时也是如此,这显然是我想避免的。
这就是我在我的中注册服务人员的方式main.js
:
// Install service worker for offline use and caching
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/service-worker.js', {scope: '/'});
}
我现在的service-worker.js
:
const OFFLINE_URL = '/mysite/offline';
const CACHE_NAME = 'mysite-static-v1';
self.addEventListener('install', (event) => {
event.waitUntil(
// Cache the offline page when installing the service worker
fetch(OFFLINE_URL, { credentials: 'include' }).then(response =>
caches.open(CACHE_NAME).then(cache => cache.put(OFFLINE_URL, response)),
),
);
});
self.addEventListener('fetch', (event) => {
const requestURL = new URL(event.request.url);
if (requestURL.origin === location.origin) {
// Load static assets from cache if network is down
if (/\.(css|js|woff|woff2|ttf|eot|svg)$/.test(requestURL.pathname)) {
event.respondWith(
caches.open(CACHE_NAME).then(cache =>
caches.match(event.request).then((result) => {
if (navigator.onLine === false) {
// We are offline so return the cached version immediately, null or not.
return result;
}
// We are online so let's run the request to make sure our content
// is up-to-date.
return fetch(event.request).then((response) => {
// Save the result to cache for later use.
cache.put(event.request, response.clone());
return response;
});
}),
),
);
return;
}
}
if (event.request.mode === 'navigate' && navigator.onLine === false) {
// Uh-oh, we navigated to a page while offline. Let's show our default page.
event.respondWith(caches.match(OFFLINE_URL));
return;
}
// Passthrough for everything else
event.respondWith(fetch(event.request));
});
我究竟做错了什么?
navigator.onLine
当您想要更新 UI 以指示您处于离线状态并且仅显示缓存中存在的内容时,相关事件可能会很有用。
但我会避免编写依赖于检查的服务工作者逻辑navigator.onLine
。相反,尝试做一个fetch()
无条件地提供备用响应,如果失败,则提供备用响应。这将确保您的网络应用程序按预期运行,无论是否fetch()
由于离线而失败,由于lie-fi https://www.outsystems.com/blog/lie-fi.html,或者由于您的网络服务器遇到问题。
// Other fetch handler code...
if (event.request.mode === 'navigate') {
return event.respondWith(
fetch(event.request).catch(() => caches.match(OFFLINE_URL))
);
}
// Other fetch handler code...
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)