简体   繁体   English

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

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

I understand that ServiceWorkers can grab responses out of cached network requests.我知道ServiceWorkers可以从缓存的网络请求中获取响应。

That said, is it possible to have these workers continue to update the cache in the background?也就是说,是否可以让这些工作人员继续在后台更新缓存?

Consider the following scenario: a user logs into an app where they have cached data, and is immediately greeted with "Welcome, <cached_username>!"考虑以下场景:用户登录到已缓存数据的应用程序,并立即"Welcome, <cached_username>!"

Is it be possible for the service worker to continue to make the network request after serving a cache match? Service Worker 是否可以在提供缓存匹配后继续发出网络请求 The user could've updated their username to new_username on another device, and it would be great to get the UI eventually consistent.用户可以在另一台设备new_username他们的用户名更新为new_username ,并且最终使 UI 保持一致会很棒。

I still want to make network requests, while also utilizing ServiceWorkers for that speedy initial render.我仍然想发出网络请求,同时还利用 ServiceWorkers 进行快速初始渲染。

What you're describing is very similar to the stale-while-revalidate strategy .您所描述的内容与stale-while-revalidate strategy非常相似。

The basic recipe in that cookbook doesn't include any code for having the service worker notify the client page(s) when the revalidation step finds an update, though.但是,该食谱中的基本配方不包含任何代码,用于让 Service Worker 在重新验证步骤找到更新时通知客户端页面。

If you were to use Workbox inside your service worker, you could accomplish that notification step using the workbox-broadcast-update module along with a few other modules:如果您要在 Service Worker 中使用Workbox,则可以使用workbox workbox-broadcast-update模块以及其他一些模块来完成该通知步骤:

In your 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(),
    ],
  })
);

In your web app :在您的网络应用程序中


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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM