Sejumlah pola umum, terutama seputar rute dan cache, cukup umum sehingga dapat distandarisasi menjadi resep yang dapat digunakan kembali. workbox-recipes
menyediakannya dalam paket yang mudah digunakan, sehingga memungkinkan Anda menyiapkan dan menjalankan pekerja layanan dengan cepat.
Resep
Setiap resep menggabungkan sejumlah modul Workbox, menggabungkannya ke dalam pola yang biasa digunakan. Resep di bawah ini akan menunjukkan resep yang Anda gunakan saat menggunakan modul ini, dan pola setara yang digunakannya di balik layar, jika Anda ingin menulisnya sendiri.
Penggantian offline
Resep penggantian offline memungkinkan pekerja layanan menayangkan halaman web, gambar, atau font jika terjadi error pemilihan rute untuk ketiganya, misalnya jika pengguna sedang offline dan tidak ada cache yang ditemukan. Pada versi 6.1.0 Workbox Recipes, persyaratan untuk meng-cache item ini menggunakan pra-cache telah dihapus; untuk kompatibilitas mundur, item akan dicari di pra-cache terlebih dahulu sebelum mencoba cache-nya sendiri.
Secara default, resep ini mengasumsikan bahwa halaman penggantian adalah offline.html
dan tidak ada penggantian gambar atau font. Lihat opsi penggantian offline untuk mengetahui daftar semua opsi konfigurasi.
Penggantian offline hanya akan diterapkan jika ada rute yang cocok untuk permintaan tertentu. Jika menggunakan sendiri resep penggantian offline, Anda harus membuat rute sendiri. Cara paling sederhana untuk dilakukan adalah menggunakan metode setDefaultHandler()
untuk membuat rute yang menerapkan strategi NetworkOnly
ke semua permintaan, seperti yang ditunjukkan di bawah. Urutan langkah lain, 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 hangat
Resep cache strategi hangat memungkinkan Anda memuat URL yang disediakan ke dalam cache selama fase install
pekerja layanan, meng-cache-nya dengan opsi strategi yang disediakan. Hal ini dapat digunakan sebagai alternatif untuk pra-caching jika Anda mengetahui URL tertentu yang ingin di-cache, ingin memanaskan cache rute, atau tempat serupa tempat Anda ingin meng-cache URL selama penginstalan.
Lihat opsi cache strategi pemanasan 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 cache halaman memungkinkan pekerja layanan Anda merespons permintaan untuk halaman HTML (melalui navigasi URL) dengan strategi penyimpanan dalam cache yang mengutamakan jaringan, yang dioptimalkan untuk, idealnya, memungkinkan penggantian cache terjadi 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 melihat 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
Resep cache resource statis memungkinkan pekerja layanan merespons permintaan resource statis, khususnya permintaan CSS, JavaScript, dan Web Worker, dengan strategi penyimpanan dalam cache stale-temporary-revalidate sehingga aset tersebut dapat disajikan 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
Resep cache gambar memungkinkan pekerja layanan Anda merespons permintaan gambar dengan strategi penyimpanan dalam cache cache-first sehingga setelah gambar tersedia dalam cache, pengguna tidak perlu membuat permintaan lain untuk gambar tersebut.
Secara default, resep ini menyimpan dalam cache maksimal 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
Resep Google Fonts meng-cache dua bagian permintaan Google Fonts:
- Stylesheet dengan definisi
@font-face
, yang ditautkan ke file font. - File font statis yang direvisi.
Karena stylesheet sering kali berubah, strategi penyimpanan cache stale-temporary-revalidate akan digunakan. Di sisi lain, file font itu sendiri tidak berubah dan dapat memanfaatkan strategi cache first.
Resep ini, secara default, menyimpan 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 penyimpanan dalam cache jaringan terlebih dahulu, merespons permintaan CSS, JavaScript, dan Web Worker dengan strategi stale-while-revalidate, merespons permintaan gambar dengan strategi cache terlebih dahulu, menyimpan Google Fonts dalam cache dengan benar, dan menyediakan penggantian 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
number opsional
-
maxEntries
angka opsional
ImageCacheOptions
Properti
-
cacheName
string opsional
-
matchCallback
RouteMatchCallback opsional
-
maxAgeSeconds
number opsional
-
maxEntries
angka opsional
-
plugin
WorkboxPlugin[] opsional
-
warmCache
string[] opsional
OfflineFallbackOptions
Properti
-
fontFallback
string opsional
-
imageFallback
string opsional
-
pageFallback
string opsional
PageCacheOptions
Properti
-
cacheName
string opsional
-
matchCallback
RouteMatchCallback opsional
-
networkTimeoutSeconds
angka opsional
-
plugin
WorkboxPlugin[] opsional
-
warmCache
string[] opsional
StaticResourceOptions
Properti
-
cacheName
string opsional
-
matchCallback
RouteMatchCallback opsional
-
plugin
WorkboxPlugin[] opsional
-
warmCache
string[] opsional
WarmStrategyCacheOptions
Properti
-
strategi
-
Url
string[]
Metode
googleFontsCache()
workbox-recipes.googleFontsCache(
options?: GoogleFontCacheOptions,
)
Implementasi resep penyimpanan dalam cache [Google fonts]https://developers.google.com/web/tools/workbox/guides/common-recipes#google_fonts
Parameter
-
opsi
GoogleFontCacheOptions opsional
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
-
opsi
ImageCacheOptions opsional
offlineFallback()
workbox-recipes.offlineFallback(
options?: OfflineFallbackOptions,
)
Implementasi [resep penggantian komprehensif]https://developers.google.com/web/tools/workbox/guides/advanced-recipes#comprehensive_fallbacks
. Pastikan untuk menyertakan penggantian dalam injeksi pra-cache Anda
Parameter
-
opsi
OfflineFallbackOptions opsional
pageCache()
workbox-recipes.pageCache(
options?: PageCacheOptions,
)
Implementasi resep penyimpanan dalam cache halaman dengan waktu tunggu jaringan
Parameter
-
opsi
PageCacheOptions opsional
staticResourceCache()
workbox-recipes.staticResourceCache(
options?: StaticResourceOptions,
)
Implementasi [resep file CSS dan JavaScript]https://developers.google.com/web/tools/workbox/guides/common-recipes#cache_css_and_javascript_files
Parameter
-
opsi
StaticResourceOptions opsional
warmStrategyCache()
workbox-recipes.warmStrategyCache(
options: WarmStrategyCacheOptions,
)