![](/img/trans.png)
[英]Using the Cache API to cache Web pages without Service Workers
[英]Using service workers to both use cache *and* update in background
我知道ServiceWorkers可以从缓存的网络请求中获取响应。
也就是说,是否可以让这些工作人员继续在后台更新缓存?
考虑以下场景:用户登录到已缓存数据的应用程序,并立即"Welcome, <cached_username>!"
Service Worker 是否可以在提供缓存匹配后继续发出网络请求? 用户可以在另一台设备new_username
他们的用户名更新为new_username
,并且最终使 UI 保持一致会很棒。
我仍然想发出网络请求,同时还利用 ServiceWorkers 进行快速初始渲染。
您所描述的内容与stale-while-revalidate strategy非常相似。
但是,该食谱中的基本配方不包含任何代码,用于让 Service Worker 在重新验证步骤找到更新时通知客户端页面。
如果您要在 Service Worker 中使用Workbox,则可以使用workbox workbox-broadcast-update
模块以及其他一些模块来完成该通知步骤:
在您的服务人员中:
import {registerRoute} from 'workbox-routing';
import {StaleWhileRevalidate} from 'workbox-strategies';
import {BroadcastUpdatePlugin} from 'workbox-broadcast-update';
registerRoute(
// Adjust this to match your cached data requests:
new RegExp('/api/'),
new StaleWhileRevalidate({
plugins: [
new BroadcastUpdatePlugin(),
],
})
);
在您的网络应用程序中:
navigator.serviceWorker.addEventListener('message', async (event) => {
// Optional: ensure the message came from workbox-broadcast-update
if (event.data.meta === 'workbox-broadcast-update') {
const {cacheName, updatedUrl} = event.data.payload;
// Do something with cacheName and updatedUrl.
// For example, get the cached content and update
// the content on the page.
const cache = await caches.open(cacheName);
const updatedResponse = await cache.match(updatedUrl);
const updatedText = await updatedResponse.text();
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.