使用服务工作人员在后台同时使用缓存*和*更新 [英] Using service workers to both use cache *and* update in background

查看:29
本文介绍了使用服务工作人员在后台同时使用缓存*和*更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

考虑以下场景:用户登录到缓存了数据的应用程序后,会立即看到"Welcome, <cached_username>!"

服务工作者是否可以在提供缓存匹配后继续发出网络请求?用户本可以在其他设备上将其用户名更新为new_username,如果最终获得一致的用户界面就太好了。

我仍然希望发出网络请求,同时还利用ServiceWorker进行快速初始呈现。

推荐答案

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

不过,该食谱中的基本食谱不包括任何代码,用于在重新验证步骤发现更新时让服务人员通知客户端页面。

如果您要在服务工作人员中使用Workbox,则可以使用workbox-broadcast-update module和其他几个模块来完成通知步骤:

在您的服务人员中

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

在您的Web应用中


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

这篇关于使用服务工作人员在后台同时使用缓存*和*更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆