我想使用服务工作者来缓存可以在用户离线或我的应用程序后端关闭时使用的响应。出于用户体验的原因,我想向用户显示当前无法访问应用程序的后端并且正在提供缓存内容的通知。最好的方法是什么?我可以在服务人员的响应中添加一个标题,但我不确定这是“正确的方式”......似乎应该有一个更直接的模式。这是我的服务人员代码:
self.addEventListener('fetch', event => {
console.log(`fetch event`, event);
event.respondWith(doFetch(event.request));
});
// fetch from network, fallback to cache
function doFetch(request) {
return fetch(request)
.then(response => {
return caches.open(CACHE)
.then(cache => {
cache.put(request, response.clone());
return response;
})
})
.catch(error => {
console.warn(`fetch to ${request.url} failed`, error);
return fromCache(request);
});
}
function fromCache(request) {
return caches.open(CACHE)
.then(cache => cache.match(request))
.then(match => {
if (match) {
// response.clone doesn't work here because I need to modify it
return cloneResponse(match);
} else {
throw new Error(`no match for ${request.url}`);
}
});
}
// this clones a response in a way that let's me modify it
function cloneResponse(response) {
let init = {
status: response.status,
statusText: response.statusText,
headers: { 'X-From-SW-Cache': 'true' }
};
response.headers.forEach((v, k) => {
init.headers[k] = v;
});
return response.text().then((body) => new Response(body, init));
}