สูตรสำหรับกล่องงาน

รูปแบบทั่วไปจำนวนหนึ่ง โดยเฉพาะเกี่ยวกับการกำหนดเส้นทางและการแคช เป็นรูปแบบที่พบได้บ่อยมากจนนำมาทำให้เป็นสูตรอาหารที่นำมาใช้ใหม่ได้ workbox-recipes ทำให้ส่วนขยายเหล่านี้พร้อมใช้งานในแพ็กเกจที่ใช้งานง่าย ทำให้คุณเริ่มต้นใช้งาน Service Worker ได้อย่างรวดเร็ว

สูตรอาหาร

แต่ละสูตรอาหารจะรวมโมดูลกล่องจดหมายต่างๆ เข้าด้วยกันและรวมเข้าด้วยกันเป็นรูปแบบที่ใช้กันทั่วไป สูตรอาหารด้านล่างจะแสดงสูตรอาหารที่คุณใช้เมื่อใช้โมดูลนี้ และแสดงรูปแบบที่เทียบเท่ากันซึ่งใช้ในเครื่องหากคุณต้องการเขียนรายงานด้วยตนเอง

วิดีโอสำรองแบบออฟไลน์

สูตรอาหารสำรองแบบออฟไลน์ช่วยให้ Service Worker แสดงหน้าเว็บ รูปภาพ หรือแบบอักษรได้หากเกิดข้อผิดพลาดในการกำหนดเส้นทางสำหรับ 3 อย่างนี้ เช่น หากผู้ใช้ออฟไลน์อยู่และไม่มีการคลิกแคช ใน Workbox Recipes เวอร์ชัน 6.1.0 ได้มีการนำข้อกำหนดในการแคชรายการเหล่านี้โดยใช้การแคชล่วงหน้าออก สำหรับความเข้ากันได้แบบย้อนหลัง ระบบจะมองหารายการในแคชล่วงหน้าก่อนที่จะลองใช้แคชของตัวเอง

โดยค่าเริ่มต้น สูตรนี้จะถือว่าหน้าสำรองคือ offline.html และไม่มีรูปภาพหรือแบบอักษรสำรอง โปรดดูตัวเลือกสำรองแบบออฟไลน์สำหรับรายการตัวเลือกการกำหนดค่าทั้งหมด

ระบบจะใช้เส้นทางสำรองแบบออฟไลน์ก็ต่อเมื่อมีเส้นทางที่ตรงกันสำหรับคำขอที่ระบุ หากใช้สูตรอาหารสำรองแบบออฟไลน์อยู่แล้ว คุณจะต้องสร้างเส้นทางด้วยตนเอง วิธีที่ง่ายที่สุดคือการใช้เมธอด setDefaultHandler() เพื่อสร้างเส้นทางที่ใช้กลยุทธ์ NetworkOnly กับคำขอทั้งหมด ดังที่แสดงด้านล่าง สูตรอาหารอื่นๆ เช่น แคชของหน้าเว็บ, แคชแหล่งข้อมูลแบบคงที่ หรือแคชรูปภาพ จะตั้งค่าเส้นทางสำหรับแคชที่เกี่ยวข้อง ไม่จำเป็นต้องระบุ setDefaultHandler() เมื่อใช้ทั้งวิธีสำรองแบบออฟไลน์และสูตร 1 ในสูตรอาหารเหล่านั้น

สูตรอาหาร

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);

แคชกลยุทธ์ที่อบอุ่น

สูตรแคชกลยุทธ์ที่อบอุ่นช่วยให้คุณโหลด URL ที่ระบุลงในแคชในระยะ install ของ Service Worker โดยใช้ตัวเลือกของกลยุทธ์ที่ระบุ โดยใช้เป็นทางเลือกในการแคชล่วงหน้าหากคุณทราบ 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));
});

แคชของหน้า

สูตรแคชของหน้าเว็บช่วยให้ Service Worker ตอบกลับคำขอของหน้า HTML (ผ่านการนำทาง URL) ด้วยกลยุทธ์การแคชเครือข่ายก่อน ซึ่งถ้าจะเพิ่มประสิทธิภาพ ก็จะช่วยให้แคชสำรองมาถึงได้เร็วพอสำหรับคะแนน Largest Contentful Paint ที่น้อยกว่า 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],
      }),
    ],
  })
);

แคชทรัพยากรแบบคงที่

สูตรแคชทรัพยากรแบบคงที่ช่วยให้ Service Worker ตอบกลับคำขอทรัพยากรแบบคงที่ โดยเฉพาะคำขอ 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],
      }),
    ],
  })
);

แคชรูปภาพ

สูตรแคชรูปภาพช่วยให้ Service Worker ตอบกลับคำขอรูปภาพด้วยกลยุทธ์การแคชแบบแคชเป็นอันดับแรกได้ เพื่อให้ผู้ใช้ไม่ต้องส่งคำขออีกเมื่อรูปภาพเหล่านั้นอยู่ในแคช

โดยค่าเริ่มต้น สูตรนี้แคชรูปภาพได้สูงสุด 60 ภาพ แต่ละภาพมีอายุ 30 วัน และรองรับการปรับแคชผ่านตัวเลือก 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 จะแคชทั้ง 2 ส่วนของคำขอ Google Fonts ดังนี้

  • สไตล์ชีตที่มีคำจำกัดความ @font-face ซึ่งลิงก์ไปยังไฟล์แบบอักษร
  • ไฟล์แบบอักษรแบบคงที่ที่มีการแก้ไข

เนื่องจากสไตล์ชีตสามารถเปลี่ยนแปลงบ่อย ระบบจึงใช้กลยุทธ์การแคชไม่อัปเดตขณะตรวจสอบใหม่ ในทางกลับกัน ไฟล์แบบอักษรจะไม่เปลี่ยนแปลงและใช้ประโยชน์จากกลยุทธ์แคชก่อนได้

สูตรนี้จะแคชไฟล์แบบอักษรได้สูงสุด 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,
      }),
    ],
  })
);

การใช้งานอย่างรวดเร็ว

การรวมสูตรอาหารทั้งหมดเข้าด้วยกันจะทำให้มี Service Worker ที่ตอบสนองต่อคำขอหน้าเว็บด้วยกลยุทธ์การแคชเครือข่ายเป็นอันดับแรก, ตอบสนองต่อคำขอ CSS, JavaScript และ Web Worker ด้วยกลยุทธ์ไม่อัปเดตขณะตรวจสอบใหม่, ตอบกลับคำขอรูปภาพด้วยกลยุทธ์แคชเป็นอันดับแรก, แคช Google Fonts อย่างเหมาะสม และมีไฟล์สำรองแบบออฟไลน์สำหรับคำขอหน้าเว็บ ซึ่งสามารถดำเนินการได้ด้วยสิ่งต่อไปนี้

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

pageCache();

googleFontsCache();

staticResourceCache();

imageCache();

offlineFallback();

ประเภท

GoogleFontCacheOptions

พร็อพเพอร์ตี้

  • cachePrefix

    string ไม่บังคับ

  • maxAgeSeconds

    ตัวเลข ไม่บังคับ

  • maxEntries

    ตัวเลข ไม่บังคับ

ImageCacheOptions

พร็อพเพอร์ตี้

  • cacheName

    string ไม่บังคับ

  • matchCallback

    RouteMatchCallback ไม่บังคับ

  • maxAgeSeconds

    ตัวเลข ไม่บังคับ

  • maxEntries

    ตัวเลข ไม่บังคับ

  • ปลั๊กอิน

    WorkboxPlugin[] ไม่บังคับ

  • warmCache

    string[] ไม่บังคับ

OfflineFallbackOptions

พร็อพเพอร์ตี้

  • fontFallback

    string ไม่บังคับ

  • imageFallback

    string ไม่บังคับ

  • pageFallback

    string ไม่บังคับ

PageCacheOptions

พร็อพเพอร์ตี้

  • cacheName

    string ไม่บังคับ

  • matchCallback

    RouteMatchCallback ไม่บังคับ

  • networkTimeoutSeconds

    ตัวเลข ไม่บังคับ

  • ปลั๊กอิน

    WorkboxPlugin[] ไม่บังคับ

  • warmCache

    string[] ไม่บังคับ

StaticResourceOptions

พร็อพเพอร์ตี้

  • cacheName

    string ไม่บังคับ

  • matchCallback

    RouteMatchCallback ไม่บังคับ

  • ปลั๊กอิน

    WorkboxPlugin[] ไม่บังคับ

  • warmCache

    string[] ไม่บังคับ

WarmStrategyCacheOptions

พร็อพเพอร์ตี้

วิธีการ

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 และ JavaScript]https://developers.google.com/web/tools/workbox/guides/common-recipes#cache_css_and_javascript_files

พารามิเตอร์

warmStrategyCache()

workbox-recipes.warmStrategyCache(
  options: WarmStrategyCacheOptions,
)

พารามิเตอร์