캐시된 항목이 있는 요청에 응답할 때 속도가 빠르지만 사용자가 오래된 데이터를 보게 될 수 있다는 장단점이 있습니다.
workbox-broadcast-update
패키지는 캐시된 응답이 업데이트되었음을 Window 클라이언트에 알리는 표준 방법을 제공합니다. 이는 StaleWhileRevalidate
전략과 함께 가장 일반적으로 사용됩니다.
'재검증'을 통해 이 전략의 단계에서는 응답에서 응답을 네트워크를 사용하는 경우 이 모듈은 메시지 (도메인을 통해 postMessage()
) 현재 서비스 워커의 범위 내에 있는 모든 Window 클라이언트에 적용됩니다.
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
Promise<void>
업데이트가 전송되면 해결됩니다.
-
BroadcastCacheUpdateOptions
속성
- headersToCheck
string[] 선택사항
- notifyAllClients
불리언 선택사항
- generatePayload
void 선택사항
generatePayload
함수는 다음과 같습니다.(options: CacheDidUpdateCallbackParam) => {...}
- returns
Record<stringany>
-
BroadcastUpdatePlugin
이 플러그인은 캐시된 응답이 제공될 때마다 자동으로 메시지를 브로드캐스트합니다. 이(가) 업데이트됩니다.
속성
- 생성자
void
다음을 사용하여
workbox-broadcast-update.BroadcastUpdate
인스턴스를 구성합니다.notifyIfUpdated
메서드를 호출하고 플러그인의cacheDidUpdate
콜백이 호출됩니다.constructor
함수는 다음과 같습니다.(options?: BroadcastCacheUpdateOptions) => {...}
- 옵션
BroadcastCacheUpdateOptions optional
- returns
-
메서드
responsesAreSame()
workbox-broadcast-update.responsesAreSame(
firstResponse: Response,
secondResponse: Response,
headersToCheck: string[],
): boolean
두 개의 Response's
를 사용하여 여러 헤더 값을 비교하여 동일한지 확인합니다.
매개변수
- firstResponse
응답
- secondResponse
응답
- headersToCheck
문자열[]
반환 값
-
부울