특히 라우팅 및 캐싱과 관련된 여러 일반적인 패턴은 재사용 가능한 레시피로 표준화할 만큼 일반적입니다. workbox-recipes
는 사용하기 쉬운 패키지로 이를 제공하므로 기능이 높은 서비스 워커를 사용하여 빠르게 준비하고 실행할 수 있습니다.
레시피
각 레시피는 여러 Workbox 모듈을 함께 결합하여 흔히 사용되는 패턴으로 묶습니다. 아래 레시피에서는 이 모듈을 사용할 때 사용하는 레시피와 내부적으로 사용하는 동등한 패턴을 보여줍니다.
오프라인 대체
오프라인 대체 리시피를 사용하면 서비스 워커가 웹페이지, 이미지, 글꼴 중 하나에 라우팅 오류가 있는 경우(예: 사용자가 오프라인 상태이고 캐시 히트가 없는 경우) 이를 제공할 수 있습니다. Workbox Recipes 버전 6.1.0에서는 precaching을 사용하여 이러한 항목을 캐시해야 하는 요구사항이 삭제되었습니다. 하위 호환성을 위해 자체 캐시를 시도하기 전에 먼저 사전 캐시의 항목을 찾습니다.
이 레시피는 기본적으로 대체 페이지가 offline.html
이고 이미지 또는 글꼴 대체가 없다고 가정합니다. 모든 구성 옵션의 목록은 오프라인 대체 옵션을 참조하세요.
오프라인 대체는 지정된 요청과 일치하는 경로가 있는 경우에만 적용됩니다. 오프라인 대체 레시피를 단독으로 사용하는 경우 경로를 직접 만들어야 합니다. 가장 간단한 방법은 아래와 같이 setDefaultHandler()
메서드를 사용하여 모든 요청에 NetworkOnly
전략을 적용하는 경로를 만드는 것입니다. 페이지 캐시, 정적 리소스 캐시 또는 이미지 캐시와 같은 다른 레시피에서는 각 캐시의 경로를 설정합니다. 오프라인 대체 옵션과 이러한 레시피 중 하나를 모두 사용하는 경우에는 setDefaultHandler()
가 필요하지 않습니다.
레시피
import {offlineFallback} from 'workbox-recipes';
import {setDefaultHandler} from 'workbox-routing';
import {NetworkOnly} from 'workbox-strategies';
setDefaultHandler(new NetworkOnly());
offlineFallback();
패턴
import {setCatchHandler, setDefaultHandler} from 'workbox-routing';
import {NetworkOnly} from 'workbox-strategies';
const pageFallback = 'offline.html';
const imageFallback = false;
const fontFallback = false;
setDefaultHandler(new NetworkOnly());
self.addEventListener('install', event => {
const files = [pageFallback];
if (imageFallback) {
files.push(imageFallback);
}
if (fontFallback) {
files.push(fontFallback);
}
event.waitUntil(
self.caches
.open('workbox-offline-fallbacks')
.then(cache => cache.addAll(files))
);
});
const handler = async options => {
const dest = options.request.destination;
const cache = await self.caches.open('workbox-offline-fallbacks');
if (dest === 'document') {
return (await cache.match(pageFallback)) || Response.error();
}
if (dest === 'image' && imageFallback !== false) {
return (await cache.match(imageFallback)) || Response.error();
}
if (dest === 'font' && fontFallback !== false) {
return (await cache.match(fontFallback)) || Response.error();
}
return Response.error();
};
setCatchHandler(handler);
웜 전략 캐시
따뜻한 전략 캐시 레시피를 사용하면 서비스 워커의 install
단계 중에 제공된 URL을 캐시로 로드하여 제공된 전략의 옵션으로 캐시할 수 있습니다. 캐시할 특정 URL을 알고 있거나, 경로의 캐시를 웜화하려는 경우 또는 설치 중에 URL을 캐시하려는 유사한 장소에서 이 방법을 사전 캐싱 대신 사용할 수 있습니다.
모든 구성 옵션 목록은 웜 전략 캐시 옵션을 참조하세요.
레시피
import {warmStrategyCache} from 'workbox-recipes';
import {CacheFirst} from 'workbox-strategies';
// This can be any strategy, CacheFirst used as an example.
const strategy = new CacheFirst();
const urls = ['/offline.html'];
warmStrategyCache({urls, strategy});
패턴
import {CacheFirst} from 'workbox-strategies';
// This can be any strategy, CacheFirst used as an example.
const strategy = new CacheFirst();
const urls = ['/offline.html'];
self.addEventListener('install', event => {
// handleAll returns two promises, the second resolves after all items have been added to cache.
const done = urls.map(
path =>
strategy.handleAll({
event,
request: new Request(path),
})[1]
);
event.waitUntil(Promise.all(done));
});
페이지 캐시
페이지 캐시 레시피를 사용하면 서비스 워커가 URL 탐색을 통해 HTML 페이지 요청에 네트워크 우선 캐싱 전략으로 응답할 수 있습니다. 이 전략은 최대 콘텐츠 페인트 점수가 4.0초 미만이 되도록 캐시 대체가 충분히 빨리 도착하도록 최적화됩니다.
이 레시피는 기본적으로 네트워크 제한 시간을 3초로 설정한다고 가정하고 warmCache
옵션을 통해 캐시 준비를 지원합니다. 모든 구성 옵션 목록은 페이지 캐시 옵션을 참조하세요.
레시피
import {pageCache} from 'workbox-recipes';
pageCache();
패턴
import {registerRoute} from 'workbox-routing';
import {NetworkFirst} from 'workbox-strategies';
import {CacheableResponsePlugin} from 'workbox-cacheable-response';
const cacheName = 'pages';
const matchCallback = ({request}) => request.mode === 'navigate';
const networkTimeoutSeconds = 3;
registerRoute(
matchCallback,
new NetworkFirst({
networkTimeoutSeconds,
cacheName,
plugins: [
new CacheableResponsePlugin({
statuses: [0, 200],
}),
],
})
);
정적 리소스 캐시
정적 리소스 캐시 레시피를 사용하면 서비스 워커가 정적 리소스, 특히 CSS, JavaScript 및 Web Worker 요청에 대한 stale-while-revalidate 캐싱 전략을 사용하여 이러한 애셋을 캐시에서 빠르게 제공하고 백그라운드에서 업데이트할 수 있습니다.
이 레시피는 warmCache
옵션을 통해 캐시 준비를 지원합니다. 모든 구성 옵션 목록은 정적 리소스 캐시 옵션을 참고하세요.
레시피
import {staticResourceCache} from 'workbox-recipes';
staticResourceCache();
패턴
import {registerRoute} from 'workbox-routing';
import {StaleWhileRevalidate} from 'workbox-strategies';
import {CacheableResponsePlugin} from 'workbox-cacheable-response';
const cacheName = 'static-resources';
const matchCallback = ({request}) =>
// CSS
request.destination === 'style' ||
// JavaScript
request.destination === 'script' ||
// Web Workers
request.destination === 'worker';
registerRoute(
matchCallback,
new StaleWhileRevalidate({
cacheName,
plugins: [
new CacheableResponsePlugin({
statuses: [0, 200],
}),
],
})
);
이미지 캐시
이미지 캐시 레시피를 사용하면 서비스 워커가 캐시 우선 캐싱 전략을 사용하여 이미지 요청에 응답할 수 있으므로 이미지를 캐시에서 사용할 수 있게 되면 사용자가 이 이미지에 대해 다른 요청을 할 필요가 없습니다.
이 레시피는 기본적으로 30일 동안 최대 60개의 이미지를 캐시하고 warmCache
옵션을 통해 캐시 준비를 지원합니다. 모든 구성 옵션 목록은 이미지 캐시 옵션을 참고하세요.
레시피
import {imageCache} from 'workbox-recipes';
imageCache();
패턴
import {registerRoute} from 'workbox-routing';
import {CacheFirst} from 'workbox-strategies';
import {CacheableResponsePlugin} from 'workbox-cacheable-response';
import {ExpirationPlugin} from 'workbox-expiration';
const cacheName = 'images';
const matchCallback = ({request}) => request.destination === 'image';
const maxAgeSeconds = 30 * 24 * 60 * 60;
const maxEntries = 60;
registerRoute(
matchCallback,
new CacheFirst({
cacheName,
plugins: [
new CacheableResponsePlugin({
statuses: [0, 200],
}),
new ExpirationPlugin({
maxEntries,
maxAgeSeconds,
}),
],
})
);
Google Fonts 캐시
Google Fonts 레시피는 Google Fonts 요청의 두 부분을 캐시합니다.
- 글꼴 파일에 연결되는
@font-face
정의가 포함된 스타일시트입니다. - 버전이 지정된 정적 글꼴 파일입니다.
스타일시트는 자주 변경될 수 있으므로 stale-while-revalidate 캐싱 전략이 사용됩니다. 반면 글꼴 파일 자체는 변경되지 않으며 캐시 우선 전략을 활용할 수 있습니다.
이 레시피는 기본적으로 최대 30개의 글꼴 파일을 각각 1년 동안 캐시합니다. 모든 구성 옵션 목록을 보려면 Google Fonts 캐시 옵션을 참고하세요.
레시피
import {googleFontsCache} from 'workbox-recipes';
googleFontsCache();
패턴
import {registerRoute} from 'workbox-routing';
import {StaleWhileRevalidate} from 'workbox-strategies';
import {CacheFirst} from 'workbox-strategies';
import {CacheableResponsePlugin} from 'workbox-cacheable-response';
import {ExpirationPlugin} from 'workbox-expiration';
const sheetCacheName = 'google-fonts-stylesheets';
const fontCacheName = 'google-fonts-webfonts';
const maxAgeSeconds = 60 * 60 * 24 * 365;
const maxEntries = 30;
registerRoute(
({url}) => url.origin === 'https://fonts.googleapis.com',
new StaleWhileRevalidate({
cacheName: sheetCacheName,
})
);
// Cache the underlying font files with a cache-first strategy for 1 year.
registerRoute(
({url}) => url.origin === 'https://fonts.gstatic.com',
new CacheFirst({
cacheName: fontCacheName,
plugins: [
new CacheableResponsePlugin({
statuses: [0, 200],
}),
new ExpirationPlugin({
maxAgeSeconds,
maxEntries,
}),
],
})
);
빠른 사용
모든 레시피를 함께 결합하면 네트워크 우선 캐싱 전략으로 페이지 요청에 응답하고, stale-while-revalidate 전략으로 CSS, JavaScript 및 Web Worker 요청에 응답하고, 캐시 우선 전략으로 이미지 요청에 응답하고, Google Fonts를 적절하게 캐시하고, 페이지 요청에 대한 오프라인 대체를 제공하는 서비스 워커를 만들 수 있습니다. 이 작업은 모두 다음과 같은 방법으로 수행할 수 있습니다.
import {
pageCache,
imageCache,
staticResourceCache,
googleFontsCache,
offlineFallback,
} from 'workbox-recipes';
pageCache();
googleFontsCache();
staticResourceCache();
imageCache();
offlineFallback();
유형
GoogleFontCacheOptions
속성
-
cachePrefix
문자열(선택사항)
-
maxAgeSeconds
번호 선택사항
-
maxEntries
번호 선택사항
ImageCacheOptions
속성
-
cacheName
문자열 선택사항
-
matchCallback
RouteMatchCallback 선택사항
-
maxAgeSeconds
번호 선택사항
-
maxEntries
번호 선택사항
-
플러그인
WorkboxPlugin[] 선택사항
-
warmCache
string[] 선택사항
OfflineFallbackOptions
속성
-
fontFallback
문자열 선택사항
-
imageFallback
문자열 선택사항
-
pageFallback
문자열(선택사항)
PageCacheOptions
속성
-
cacheName
문자열 선택사항
-
matchCallback
RouteMatchCallback 선택사항
-
networkTimeoutSeconds
숫자 선택사항
-
플러그인
WorkboxPlugin[] 선택사항
-
warmCache
string[] 선택사항
StaticResourceOptions
속성
-
cacheName
문자열 선택사항
-
matchCallback
RouteMatchCallback 선택사항
-
플러그인
WorkboxPlugin[] 선택사항
-
warmCache
string[] 선택사항
WarmStrategyCacheOptions
속성
-
전략
-
URL
문자열[]
메서드
googleFontsCache()
workbox-recipes.googleFontsCache(
options?: GoogleFontCacheOptions,
)
[Google Fonts]https://developers.google.com/web/tools/workbox/guides/common-recipes#google_fonts
캐싱 레시피 구현
매개변수
-
옵션
imageCache()
workbox-recipes.imageCache(
options?: ImageCacheOptions,
)
[이미지 캐싱 레시피]https://developers.google.com/web/tools/workbox/guides/common-recipes#caching_images
의 구현
매개변수
-
옵션
ImageCacheOptions 선택사항
offlineFallback()
workbox-recipes.offlineFallback(
options?: OfflineFallbackOptions,
)
[포괄적인 대체 레시피]https://developers.google.com/web/tools/workbox/guides/advanced-recipes#comprehensive_fallbacks
의 구현입니다. 사전 캐시 삽입에 대체를 포함해야 합니다.
매개변수
-
옵션
매개변수
-
옵션
PageCacheOptions 선택사항
staticResourceCache()
workbox-recipes.staticResourceCache(
options?: StaticResourceOptions,
)
[CSS 및 JavaScript 파일 레시피] 구현https://developers.google.com/web/tools/workbox/guides/common-recipes#cache_css_and_javascript_files
매개변수
-
옵션
warmStrategyCache()
workbox-recipes.warmStrategyCache(
options: WarmStrategyCacheOptions,
)