resep-resep-workbox

Sejumlah pola umum, terutama seputar perutean dan caching, sudah cukup umum sehingga dapat distandardisasi menjadi resep yang dapat digunakan kembali. workbox-recipes menyediakannya dalam paket yang mudah digunakan, sehingga Anda dapat memulai dan menjalankannya dengan pekerja layanan yang sangat fungsional dengan cepat.

Resep

Setiap resep menggabungkan sejumlah modul Workbox, dan mengelompokkannya ke dalam pola yang umum digunakan. Resep di bawah ini akan menunjukkan resep yang Anda gunakan saat menggunakan modul ini, dan pola yang setara yang digunakannya di balik layar, jika Anda ingin menulisnya sendiri.

Penggantian offline

Urutan langkah penggantian offline memungkinkan pekerja layanan menyajikan halaman web, gambar, atau font jika terjadi error perutean untuk salah satu dari ketiganya, misalnya jika pengguna offline dan tidak ada cache yang ditemukan. Pada Workbox Recipes versi 6.1.0, persyaratan untuk meng-cache item ini menggunakan precaching telah dihapus. Untuk kompatibilitas mundur, sistem akan mencari item dalam precache terlebih dahulu sebelum mencoba cache-nya sendiri.

Urutan langkah ini, secara default, mengasumsikan halaman penggantian adalah offline.html dan tidak ada penggantian gambar atau font. Lihat opsi penggantian offline untuk daftar semua opsi konfigurasi.

Penggantian offline hanya akan diterapkan jika ada rute yang cocok untuk permintaan tertentu. Jika Anda menggunakan urutan langkah penggantian offline sendiri, Anda harus membuat rute sendiri. Cara paling mudah untuk dilakukan adalah menggunakan metode setDefaultHandler() untuk membuat rute yang menerapkan strategi NetworkOnly ke semua permintaan, seperti yang ditunjukkan di bawah ini. Urutan langkah lainnya, seperti cache halaman, cache resource statis, atau cache gambar, menyiapkan rute untuk cache masing-masing. setDefaultHandler() tidak diperlukan saat menggunakan penggantian offline dan salah satu urutan langkah tersebut.

Resep

import {offlineFallback} from 'workbox-recipes';
import {setDefaultHandler} from 'workbox-routing';
import {NetworkOnly} from 'workbox-strategies';

setDefaultHandler(new NetworkOnly());

offlineFallback();

Pola

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

Cache strategi warm

Resep cache strategi warm memungkinkan Anda memuat URL yang disediakan ke dalam cache selama fase install pekerja layanan, menyimpannya dalam cache dengan opsi strategi yang disediakan. Ini dapat digunakan sebagai alternatif untuk pra-cache jika Anda mengetahui URL tertentu yang ingin di-cache, ingin menghangatkan cache rute, atau tempat serupa tempat Anda ingin meng-cache URL selama penginstalan.

Lihat opsi cache strategi hangat untuk mengetahui daftar semua opsi konfigurasi.

Resep

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

Pola

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

Cache halaman

Urutan langkah cache halaman memungkinkan pekerja layanan Anda merespons permintaan untuk halaman HTML (melalui navigasi URL) dengan strategi caching yang mengutamakan jaringan, yang dioptimalkan agar, idealnya, memungkinkan penggantian cache muncul cukup cepat untuk skor largest contentful paint kurang dari 4,0 detik.

Urutan langkah ini, secara default, mengasumsikan waktu tunggu jaringan adalah 3 detik dan mendukung pemanasan cache melalui opsi warmCache. Lihat opsi cache halaman untuk mengetahui daftar semua opsi konfigurasi.

Resep

import {pageCache} from 'workbox-recipes';

pageCache();

Pola

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],
      }),
    ],
  })
);

Cache resource statis

Urutan langkah cache resource statis memungkinkan pekerja layanan merespons permintaan untuk resource statis, khususnya permintaan CSS, JavaScript, dan Web Worker, dengan strategi caching buang-saat-validasi ulang sehingga aset tersebut dapat disalurkan dengan cepat dari cache dan diperbarui di latar belakang

Resep ini mendukung pemanasan cache melalui opsi warmCache. Lihat opsi cache resource statis untuk mengetahui daftar semua opsi konfigurasi.

Resep

import {staticResourceCache} from 'workbox-recipes';

staticResourceCache();

Pola

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],
      }),
    ],
  })
);

Cache gambar

Urutan langkah cache gambar memungkinkan pekerja layanan merespons permintaan gambar dengan strategi caching yang mengutamakan cache, sehingga setelah tersedia dalam cache, pengguna tidak perlu membuat permintaan lain untuk gambar tersebut.

Resep ini, secara default, meng-cache maksimum 60 gambar, masing-masing selama 30 hari dan mendukung pemanasan cache melalui opsi warmCache. Lihat opsi cache gambar untuk mengetahui daftar semua opsi konfigurasi.

Resep

import {imageCache} from 'workbox-recipes';

imageCache();

Pola

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,
      }),
    ],
  })
);

Cache Google Fonts

Urutan langkah Google Fonts meng-cache dua bagian permintaan Google Fonts:

  • Stylesheet dengan definisi @font-face, yang menautkan ke file font.
  • File font statis yang direvisi.

Karena stylesheet dapat sering berubah, strategi penyimpanan dalam cache yang tidak berlaku saat validasi ulang digunakan. Di sisi lain, file font itu sendiri tidak berubah dan dapat memanfaatkan strategi cache terlebih dahulu.

Resep ini, secara default, meng-cache maksimum 30 file font, masing-masing selama satu tahun. Lihat opsi cache Google Fonts untuk daftar semua opsi konfigurasi.

Resep

import {googleFontsCache} from 'workbox-recipes';

googleFontsCache();

Pola

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,
      }),
    ],
  })
);

Penggunaan cepat

Menggabungkan semua resep akan menghasilkan pekerja layanan yang merespons permintaan halaman dengan strategi caching yang mengutamakan jaringan, merespons permintaan CSS, JavaScript, dan Web Worker dengan strategi yang tidak berlaku saat validasi ulang, merespons permintaan gambar dengan strategi cache terlebih dahulu, meng-cache Google Fonts dengan benar, dan menyediakan fallback offline untuk permintaan halaman. Semua ini dapat dilakukan dengan hal berikut:

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

pageCache();

googleFontsCache();

staticResourceCache();

imageCache();

offlineFallback();

Jenis

GoogleFontCacheOptions

Properti

  • cachePrefix

    string opsional

  • maxAgeSeconds

    nomor opsional

  • maxEntries

    nomor opsional

ImageCacheOptions

Properti

  • cacheName

    string opsional

  • matchCallback
  • maxAgeSeconds

    nomor opsional

  • maxEntries

    nomor opsional

  • plugin

    WorkboxPlugin[] opsional

  • warmCache

    string[] opsional

OfflineFallbackOptions

Properti

  • fontFallback

    string opsional

  • imageFallback

    string opsional

  • pageFallback

    string opsional

PageCacheOptions

Properti

  • cacheName

    string opsional

  • matchCallback
  • networkTimeoutSeconds

    nomor opsional

  • plugin

    WorkboxPlugin[] opsional

  • warmCache

    string[] opsional

StaticResourceOptions

Properti

WarmStrategyCacheOptions

Properti

Metode

googleFontsCache()

workbox-recipes.googleFontsCache(
  options?: GoogleFontCacheOptions,
)

Implementasi resep caching [Google font]https://developers.google.com/web/tools/workbox/guides/common-recipes#google_fonts

Parameter

imageCache()

workbox-recipes.imageCache(
  options?: ImageCacheOptions,
)

Implementasi [resep penyimpanan gambar dalam cache]https://developers.google.com/web/tools/workbox/guides/common-recipes#caching_images

Parameter

offlineFallback()

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

Implementasi [urutan langkah penggantian komprehensif]https://developers.google.com/web/tools/workbox/guides/advanced-recipes#comprehensive_fallbacks. Pastikan untuk menyertakan fallback dalam injeksi pra-cache Anda

Parameter

pageCache()

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

Implementasi urutan langkah penyimpanan halaman dalam cache dengan waktu tunggu jaringan

Parameter

staticResourceCache()

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

Implementasi [urutan file CSS dan JavaScript]https://developers.google.com/web/tools/workbox/guides/common-recipes#cache_css_and_javascript_files

Parameter

warmStrategyCache()

workbox-recipes.warmStrategyCache(
  options: WarmStrategyCacheOptions,
)

Parameter