작업 상자 레시피

여러 가지 공통 패턴, 특히 라우팅캐싱은 재사용 가능한 레시피로 표준화할 수 있을 만큼 일반적입니다. workbox-recipes를 사용하면 사용하기 쉬운 패키지로 이를 사용할 수 있으므로 고성능 서비스 워커를 빠르게 준비하고 실행할 수 있습니다.

Recipes

각 레시피는 여러 Workbox 모듈을 함께 결합하여 흔히 사용되는 패턴으로 묶습니다. 아래 레시피에서는 사용자가 직접 작성할 때 이 모듈을 사용할 때 사용하는 레시피와 내부적으로 사용하는 패턴을 보여줍니다.

오프라인 대체

오프라인 대체 레시피를 사용하면, 예를 들어 사용자가 오프라인 상태이고 캐시에 있음이 없는 경우와 같이 세 가지 모두에 라우팅 오류가 있는 경우 서비스 워커가 웹페이지, 이미지 또는 글꼴을 제공할 수 있습니다. Workbox 레시피 버전 6.1.0에서는 프리캐싱을 사용하여 이러한 항목을 캐시해야 하는 요구 사항이 삭제되었습니다. 이전 버전과의 호환성을 위해 자체 캐시를 시도하기 전에 먼저 사전 캐시에서 항목을 찾습니다.

이 레시피에서는 기본적으로 대체 페이지가 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],
      }),
    ],
  })
);

정적 리소스 캐시

정적 리소스 캐시 레시피를 사용하면 서비스 워커가 stale-while-revalidate 캐싱 전략을 사용하여 정적 리소스, 특히 CSS, JavaScript 및 Web Worker 요청에 대한 요청에 응답할 수 있으므로, 이러한 애셋을 캐시에서 빠르게 제공하고 백그라운드에서 업데이트할 수 있습니다.

이 레시피는 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 캐싱 전략이 사용됩니다. 반면 글꼴 파일 자체는 변경되지 않으며 캐시 우선 전략을 활용할 수 있습니다.

이 레시피는 기본적으로 각각 1년 동안 최대 30개의 글꼴 파일을 캐시합니다. 모든 구성 옵션 목록은 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,
      }),
    ],
  })
);

빠른 사용

모든 레시피를 결합하면 네트워크 우선 캐싱 전략으로 페이지 요청에 응답하고, 비활성 재검증 전략으로 CSS, JavaScript, 웹 워커 요청에 응답하고, 캐시 우선 전략으로 이미지 요청에 응답하고, Google Fonts를 적절하게 캐시하고, 페이지 요청에 대한 오프라인 대체를 제공하는 서비스 워커가 생성됩니다. 다음을 사용하면 됩니다.

import {
  pageCache,
  imageCache,
  staticResourceCache,
  googleFontsCache,
  offlineFallback,
} from 'workbox-recipes';

pageCache();

googleFontsCache();

staticResourceCache();

imageCache();

offlineFallback();

유형

GoogleFontCacheOptions

속성

  • cachePrefix

    문자열 선택사항

  • maxAgeSeconds

    number 선택사항

  • maxEntries

    number 선택사항

ImageCacheOptions

속성

  • cacheName

    문자열 선택사항

  • matchCallback

    RouteMatchCallback 선택사항

  • maxAgeSeconds

    number 선택사항

  • maxEntries

    number 선택사항

  • 플러그인

    WorkboxPlugin[] 선택사항

  • warmCache

    string[] 선택사항

OfflineFallbackOptions

속성

  • fontFallback

    문자열 선택사항

  • imageFallback

    문자열 선택사항

  • pageFallback

    문자열 선택사항

PageCacheOptions

속성

  • cacheName

    문자열 선택사항

  • matchCallback

    RouteMatchCallback 선택사항

  • networkTimeoutSeconds

    number 선택사항

  • 플러그인

    WorkboxPlugin[] 선택사항

  • warmCache

    string[] 선택사항

StaticResourceOptions

속성

  • cacheName

    문자열 선택사항

  • matchCallback

    RouteMatchCallback 선택사항

  • 플러그인

    WorkboxPlugin[] 선택사항

  • warmCache

    string[] 선택사항

WarmStrategyCacheOptions

속성

  • 전략
  • urls

    문자열[]

방법

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의 구현

매개변수

offlineFallback()

workbox-recipes.offlineFallback(
  options?: OfflineFallbackOptions,
)

[포괄적인 대체 레시피]https://developers.google.com/web/tools/workbox/guides/advanced-recipes#comprehensive_fallbacks의 구현입니다. 사전 캐시 삽입에 대체를 포함해야 합니다.

매개변수

pageCache()

workbox-recipes.pageCache(
  options?: PageCacheOptions,
)

네트워크 시간 제한이 있는 페이지 캐싱 레시피의 구현

매개변수

staticResourceCache()

workbox-recipes.staticResourceCache(
  options?: StaticResourceOptions,
)

[CSS 및 자바스크립트 파일 레시피]https://developers.google.com/web/tools/workbox/guides/common-recipes#cache_css_and_javascript_files의 구현

매개변수

warmStrategyCache()

workbox-recipes.warmStrategyCache(
  options: WarmStrategyCacheOptions,
)

매개변수