此文主要描述Workbox的示例緩存策略
緩存字體(以google服務(wù)為例)
Google字體服務(wù)由兩部分組成:
- 包含@font-face的樣式文件
- 內(nèi)部靜態(tài)的,修訂的字體庫(kù)。
我們知道,樣式文件更新比較頻繁,優(yōu)先用“StaleWhileRevalidate”的緩存策略; 而字體庫(kù)本身不會(huì)改變,所以用“cache first”緩存策略。
在這里,我們將緩存的”字體庫(kù)“的時(shí)間限制為一年(匹配HTTP Cache-Control標(biāo)頭),將最大條目限制為30(以確保我們不會(huì)在用戶的設(shè)備上占用過多的存儲(chǔ)空間)
// Cache the Google Fonts stylesheets with a stale-while-revalidate strategy.
workbox.routing.registerRoute(
/^https:\/\/fonts\.googleapis\.com/,
new workbox.strategies.StaleWhileRevalidate({
cacheName: 'google-fonts-stylesheets',
})
);
// Cache the underlying font files with a cache-first strategy for 1 year.
workbox.routing.registerRoute(
/^https:\/\/fonts\.gstatic\.com/,
new workbox.strategies.CacheFirst({
cacheName: 'google-fonts-webfonts',
plugins: [
new workbox.cacheableResponse.Plugin({
statuses: [0, 200],
}),
new workbox.expiration.Plugin({
maxAgeSeconds: 60 * 60 * 24 * 365,
maxEntries: 30,
}),
],
})
);
緩存圖片
你可能希望通過匹配文件“后綴名”,采用“cache-first”策略來緩存圖片
workbox.routing.registerRoute(
/\.(?:png|gif|jpg|jpeg|webp|svg)$/,
new workbox.strategies.CacheFirst({
cacheName: 'images',
plugins: [
new workbox.expiration.Plugin({
maxEntries: 60,
maxAgeSeconds: 30 * 24 * 60 * 60, // 30 Days
}),
],
})
);
緩存css和JS文件
您可能希望對(duì)未預(yù)先緩存的CSS和JavaScript文件,使用stale-while-revalidate策略。
workbox.routing.registerRoute(
/\.(?:js|css)$/,
new workbox.strategies.StaleWhileRevalidate({
cacheName: 'static-resources',
})
);
從多個(gè)來源緩存內(nèi)容
您可以創(chuàng)建正則表達(dá)式來緩存來自單個(gè)路徑中的多個(gè)源的類似請(qǐng)求。例如下面,緩存來自googleapis.com和gstatic.com來源的資源
workbox.routing.registerRoute(
/.*(?:googleapis|gstatic)\.com/,
new workbox.strategies.StaleWhileRevalidate(),
);
其實(shí)就是下面的替代方案
workbox.routing.registerRoute(
/.*(?:googleapis)\.com/,
new workbox.strategies.StaleWhileRevalidate({
cacheName: 'googleapis',
})
);
workbox.routing.registerRoute(
/.*(?:gstatic)\.com/,
new workbox.strategies.StaleWhileRevalidate({
cacheName: 'gstatic',
})
);
針對(duì)來源設(shè)置緩存規(guī)則
例如,下面的示例緩存最多50個(gè)請(qǐng)求,最多5分鐘。
workbox.routing.registerRoute(
'https://hacker-news.firebaseio.com/v0/api',
new workbox.strategies.CacheFirst({
cacheName: 'stories',
plugins: [
new workbox.expiration.Plugin({
maxEntries: 50, // 50個(gè)
maxAgeSeconds: 5 * 60, // 5 分鐘
}),
new workbox.cacheableResponse.Plugin({
statuses: [0, 200],
}),
],
})
);
強(qiáng)制網(wǎng)絡(luò)請(qǐng)求超時(shí)
可能存在一些網(wǎng)絡(luò)請(qǐng)求,他們花費(fèi)的時(shí)間很長(zhǎng),那么通過一些配置,讓任何在超時(shí)內(nèi)無(wú)法響應(yīng)的網(wǎng)絡(luò)請(qǐng)求都強(qiáng)制回退到緩存獲取。 為此,您可以使用NetworkFirst策略并配置networkTimeoutSeconds選項(xiàng)。
workbox.routing.registerRoute(
'https://hacker-news.firebaseio.com/v0/api',
new workbox.strategies.NetworkFirst({
networkTimeoutSeconds: 3,
cacheName: 'stories',
plugins: [
new workbox.expiration.Plugin({
maxEntries: 50,
maxAgeSeconds: 5 * 60, // 5 minutes
}),
],
})
);
從特定子目錄緩存資源
您可以使用正則表達(dá)式輕松地將請(qǐng)求路由匹配到特定目錄中的文件。如果我們想將請(qǐng)求路由匹配到/static/中的文件,我們可以使用正則表達(dá)式new RegExp('/ static /'),如下所示:
workbox.routing.registerRoute(
new RegExp('/static/'),
new workbox.strategies.StaleWhileRevalidate()
);
基于資源類型的緩存資源
你可以使用RequestDestination確定策略的請(qǐng)求目標(biāo)類型。比如,當(dāng)目標(biāo)是<audio>數(shù)據(jù)
workbox.routing.registerRoute(
// Custom `matchCallback` function
({event}) => event.request.destination === 'audio',
new workbox.strategies.CacheFirst({
cacheName: 'audio',
plugins: [
new workbox.expiration.Plugin({
maxEntries: 60,
maxAgeSeconds: 30 * 24 * 60 * 60, // 30 Days
}),
],
})
);
從Web應(yīng)用程序代碼訪問緩存
Cache Storage API可用于service worker和客戶端(window)的上下文中。如果要更改緩存 - 添加或刪除條目,或從Web應(yīng)用程序的上下文獲取緩存URL列表,您可以直接執(zhí)行此操作,而無(wú)需通過postMessage()與service worker通信。
例如,如果要將URL添加到給定緩存,以響應(yīng)Web應(yīng)用程序中的用戶操作,則可以使用如下代碼:
// Inside app.js:
async function addToCache(urls) {
const myCache = await window.caches.open('my-cache');
await myCache.addAll(urls);
}
//隨時(shí)調(diào)用addToCache。例如,在DOM加載后,添加某些路徑到緩存:
window.addEventListener('load', () => {
// ...determine the list of related URLs for the current page...
addToCache(['/static/relatedUrl1', '/static/relatedUrl2']);
});
在service worker設(shè)置緩存規(guī)則時(shí),可以引用緩存名稱
// Inside service-worker.js:
workbox.routing.registerRoute(
new RegExp('/static/'),
new workbox.strategies.StaleWhileRevalidate({
//'my-cache是之前已經(jīng)配置緩存名稱,這里可以直接指定使用
cacheName: 'my-cache',
})
);
以上為workbox 官網(wǎng)common-recipes章節(jié)的搬運(yùn),如理解有誤,請(qǐng)指正,感謝;
原文: common-recipes