使用服务工作者在后台同时使用缓存 * 和 * 更新

Using service workers to both use cache *and* update in background

我知道 ServiceWorkers 可以从缓存的网络请求中获取响应。

也就是说,是否可以让这些worker在后台继续更新缓存?

考虑以下场景:用户登录到他们缓存数据的应用程序,并立即收到 "Welcome, <cached_username>!"

的问候

Service Worker 是否可以在提供缓存匹配后继续发出网络请求?用户可以在另一台设备上将他们的用户名更新为 new_username,如果能使 UI 最终保持一致就好了。

我仍然想发出网络请求,同时还想利用 ServiceWorkers 进行快速初始渲染。

您描述的内容与 stale-while-revalidate strategy 非常相似。

不过,该说明书中的基本方法不包含任何让服务工作者在重新验证步骤发现更新时通知客户端页面的代码。

如果您要将 Workbox inside your service worker, you could accomplish that notification step using the workbox-broadcast-update module 与其他一些模块一起使用:

在你的 service worker 中:

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();
  }
});