簡體   English   中英

使用服務工作者在后台同時使用緩存 * 和 * 更新

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM