回應含快取項目的要求時,如果回應速度很快 有利於使用者看到過時的資料。
workbox-broadcast-update
套件提供標準方式,可通知 Window 用戶端已更新快取回應。最常見的用途是與 StaleWhileRevalidate
策略。
每當該策略的「重新驗證」步驟從網路擷取的回應與先前快取的回應不同,這個模組就會透過 postMessage()
將訊息傳送至目前服務工作者範圍內的所有 Window 用戶端。
視窗用戶端可以監聽更新並採取適當行動,例如 自動顯示訊息,告知使用者有更新 可以使用。
如何決定更新?
系統會比較快取和新 Response
物件的特定標頭,如果任何標頭的值不同,就會視為更新。
根據預設,系統會比較 Content-Length
、ETag
和 Last-Modified
標頭。
Workbox 使用標頭值而不是位元組對位元組的比較 尤其是對 大型回應
使用廣播更新
這個程式庫應該與 StaleWhileRevalidate
搭配使用 快取策略,因為此策略需要 立即回應,也提供更新機制 以非同步的方式快取
如要播送更新,只要將 broadcastUpdate.BroadcastUpdatePlugin
新增到 策略選項
import {registerRoute} from 'workbox-routing'; import {StaleWhileRevalidate} from 'workbox-strategies'; import {BroadcastUpdatePlugin} from 'workbox-broadcast-update'; registerRoute( ({url}) => url.pathname.startsWith('/api/'), new StaleWhileRevalidate({ plugins: [new BroadcastUpdatePlugin()], }) );
在網頁應用程式中,DOMContentLoaded
之前 事件觸發後,您可以監聽這些事件,例如:
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(); } });
訊息格式
在網頁應用程式中叫用 message
事件監聽器時, event.data
屬性將具有以下格式:
{ type: 'CACHE_UPDATED', meta: 'workbox-broadcast-update', // The two payload values vary depending on the actual update: payload: { cacheName: 'the-cache-name', updatedURL: 'https://example.com/' } }
自訂要檢查的標頭
如要自訂要檢查的標頭,請設定 headersToCheck
資源。
import {registerRoute} from 'workbox-routing'; import {StaleWhileRevalidate} from 'workbox-strategies'; import {BroadcastUpdatePlugin} from 'workbox-broadcast-update'; registerRoute( ({url}) => url.pathname.startsWith('/api/'), new StaleWhileRevalidate({ plugins: [ new BroadcastUpdatePlugin({ headersToCheck: ['X-My-Custom-Header'], }), ], }) );
進階用途
雖然大多數開發人員會將 workbox-broadcast-update
用於特定策略的外掛程式,如上方所示,但也可以在服務工作者程式碼中使用基礎邏輯。
import {BroadcastCacheUpdate} from 'workbox-broadcast-update'; const broadcastUpdate = new BroadcastCacheUpdate({ headersToCheck: ['X-My-Custom-Header'], }); const cacheName = 'api-cache'; const request = new Request('https://example.com/api'); const cache = await caches.open(cacheName); const oldResponse = await cache.match(request); const newResponse = await fetch(request); broadcastUpdate.notifyIfUpdated({ cacheName, oldResponse, newResponse, request, );
類型
BroadcastCacheUpdate
在快取回應更新時,使用 postMessage()
API 通知所有已開啟的視窗/分頁。
為了提升效率,我們不會比較基礎回應主體。 系統只會檢查特定回應標頭。
屬性
- 建構函式
void
建構具有特定
channelName
的 BroadcastCacheUpdate 執行個體,以便 開啟廣播訊息constructor
函式如下所示:(options?: BroadcastCacheUpdateOptions) => {...}
- returns
-
- notifyIfUpdated
void
比較兩個回應,並在回應不同時,透過
postMessage()
將訊息傳送至所有視窗用戶端。兩種回應都不可以 不透明。發布的訊息採用以下格式 (其中
payload
可以 透過建立執行個體的generatePayload
選項進行自訂 提供者:{ type: 'CACHE_UPDATED', meta: 'workbox-broadcast-update', payload: { cacheName: 'the-cache-name', updatedURL: 'https://example.com/' } }
notifyIfUpdated
函式如下所示:(options: CacheDidUpdateCallbackParam) => {...}
- returns
承諾<void>
更新傳送後即會解決。
-
BroadcastCacheUpdateOptions
屬性
- headersToCheck
string[] 選填
- notifyAllClients
boolean 選填
- generatePayload
void 選填
generatePayload
函式如下所示:(options: CacheDidUpdateCallbackParam) => {...}
- returns
Record<stringany>
-
BroadcastUpdatePlugin
這個外掛程式會在收到快取回應時自動廣播訊息 已更新。
屬性
- 建構函式
void
使用傳入的選項建構
workbox-broadcast-update.BroadcastUpdate
例項,並在每次叫用外掛程式的cacheDidUpdate
回呼時呼叫其notifyIfUpdated
方法。constructor
函式如下所示:(options?: BroadcastCacheUpdateOptions) => {...}
- returns
-
方法
responsesAreSame()
workbox-broadcast-update.responsesAreSame(
firstResponse: Response,
secondResponse: Response,
headersToCheck: string[],
): boolean
指定兩個 Response's
,比較多個標頭值,瞭解 會保持不變
參數
- firstResponse
回應
- secondResponse
回應
- headersToCheck
string[]
傳回
-
布林值