【问题标题】:Using service workers to both use cache *and* update in background使用服务工作者在后台同时使用缓存*和*更新
【发布时间】:2020-03-30 07:17:08
【问题描述】:

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

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

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

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

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

【问题讨论】:

    标签: javascript web service-worker


    【解决方案1】:

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

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

    如果您要在 Service Worker 中使用 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(),
        ],
      })
    );
    

    在您的网络应用中

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-02
      • 1970-01-01
      • 2018-09-06
      相关资源
      最近更新 更多