service-worker - 服务工作者 - 始终从网络和缓存资源提供服务
问题描述
有点挣扎,所以任何帮助将不胜感激。
我们运行的网站使用 CMS 不断更新,但希望缓存页面以供离线/缓慢使用。
我们有点不知道如何从网络提供资源,但在这样做时还要缓存它(或更新缓存的版本)。
到目前为止,这是我们的代码,但它似乎只是从缓存中加载 CSS、JS 和其他页面。
任何建议都非常感谢。
event.respondWith(
fetch(event.request)
.then(response => {
// Loads from network
debug(`Loading from network: ${response.url}`);
caches.open(config.cayg.key + config.version)
.then(cache => {
cache.put(event.request, response.clone());
});
return response;
})
.catch(response => {
// try cache
debug(`Loading from cache: ${response.url}`);
caches.match(event.request)
.then(response)
.catch(() => caches.match('/offline/')); // otherwise show offline
})
);
解决方案
Mozilla 封装了大多数用例,并为不同的配方/策略提供了示例和描述。尝试“网络或缓存”策略:
https://serviceworke.rs/strategy-network-or-cache.html
(用户界面有点不直观,演示/代码链接在页面顶部)