【发布时间】:2021-12-16 17:33:38
【问题描述】:
我是服务工作者和离线功能的新手。我创建了一个简单的 service worker 来处理网络请求并在离线时返回一个离线 html 页面。这是根据 Google 的 PWA 指南创建的。
问题是服务工作者在请求javascript文件(未缓存)时返回offline.html。相反,它应该返回网络错误或其他东西。代码如下:
const cacheName = 'offline-v1900'; //increment version to update cache
// cache these files needed for offline use
const appShellFiles = [
'./offline.html',
'./css/bootstrap.min.css',
'./img/logo/logo.png',
'./js/jquery-3.5.1.min.js',
'./js/bootstrap.min.js',
];
self.addEventListener("fetch", (e) => {
// We only want to call e.respondWith() if this is a navigation request
// for an HTML page.
// console.log(e.request.url);
e.respondWith(
(async () => {
try {
// First, try to use the navigation preload response if it's supported.
const preloadResponse = await e.preloadResponse;
if (preloadResponse) {
// console.log('returning preload response');
return preloadResponse;
}
const cachedResponse = await caches.match(e.request);
if (cachedResponse) {
// console.log(`[Service Worker] Fetching cached resource: ${e.request.url}`);
return cachedResponse;
}
// Always try the network first.
const networkResponse = await fetch(e.request);
return networkResponse;
} catch (error) {
// catch is only triggered if an exception is thrown, which is likely
// due to a network error.
// If fetch() returns a valid HTTP response with a response code in
// the 4xx or 5xx range, the catch() will NOT be called.
// console.log("Fetch failed; returning offline page instead.", error);
const cachedResponse = await caches.match('offline.html');
return cachedResponse;
}
})()
);
离线时,我在我的网站上打开一个 url,它会从缓存中加载页面,但并非所有资产都被缓存以供离线使用。因此,当发出网络请求时,比如说https://www.gstatic.com/firebasejs/9.1.3/firebase-app.js,我得到的响应是offline.html 页面的html。由于 javascript 错误,这会破坏页面。
它应该返回一个网络错误或其他东西。
【问题讨论】:
标签: javascript service-worker offline-caching