Authored by yyq

sw chche strategy

... ... @@ -7,6 +7,9 @@ const isDev = self.location.search.indexOf('dev') >= 0;
const staticDomian = isDev ? /^http:\/\/localhost:5001/i : /^https:\/\/(.*)cdn\.yoho\.cn/i;
const webDomian = isDev ? /^http:\/\/localhost:6001/i : /^https:\/\/m.yohobuy.com/;
// 定义缓存前缀
const NAME_CACHE_PREFIX = 'yoho-cache';
const precaches = [
{
url: '/offline.html',
... ... @@ -49,7 +52,7 @@ self.workbox.routing.registerRoute(args => {
}
return false;
}, self.workbox.strategies.staleWhileRevalidate({
cacheName: 'statics',
cacheName: `${NAME_CACHE_PREFIX}-statics`,
plugins: [
new self.workbox.expiration.Plugin({
maxEntries: 1000,
... ... @@ -60,29 +63,34 @@ self.workbox.routing.registerRoute(args => {
// 所有网络走 worker,异常时增加离线页面
self.workbox.routing.registerRoute(args => {
let cached = false;
let routeRegExp = new RegExp(`^\/(${CACHED_PATH.join('|')})`);
if (webDomian.test(args.url.href) &&
(routeRegExp.test(args.url.pathname) ||
args.url.pathname === '/')) {
return true;
cached = true;
}
if (args.event.request.headers.get('x-requested-with') === 'XMLHttpRequest') {
return false;
if (args.event.request.headers.get('x-requested-with') === 'XMLHttpRequest' &&
args.event.request.method !== 'GET') {
cached = false;
}
return false;
return cached;
}, args => {
return self.workbox.strategies.networkFirst({
cacheName: 'page',
cacheName: `${NAME_CACHE_PREFIX}-runtime`,
plugins: [
new self.workbox.expiration.Plugin({
maxEntries: 300,
maxAgeSeconds: 12 * 60 * 60 // 7 day
maxAgeSeconds: 12 * 60 * 60 // 12 小时
})
]
}).handle(args).then(res => {
if (res || args.event.request.mode !== 'navigate') {
// TODO report
return res;
}
... ... @@ -103,7 +111,7 @@ self.workbox.routing.registerRoute(args => {
return useWebp;
}
if (/^https?:\/\/(.*)static\.yhbimg\.com(.*)(png|jpg|jpeg)\?(imageView|imageMogr)(.*)/.test(args.url.href) &&
if (/^https:\/\/(.*)static\.yhbimg\.com(.*)(png|jpg|jpeg)\?(imageView|imageMogr)(.*)/.test(args.url.href) &&
/^(?!.*format\/).*/.test(args.url.href)) {
useWebp = true;
}
... ... @@ -118,5 +126,12 @@ self.workbox.routing.registerRoute(args => {
isReload: args.event.isReload
});
return self.workbox.strategies.networkOnly().handle(args);
return self.workbox.strategies.staleWhileRevalidate({
cacheName: `${NAME_CACHE_PREFIX}-images`,
plugins: [
new self.workbox.expiration.Plugin({
maxEntries: 100,
maxAgeSeconds: 24 * 60 * 60 // 24 小时
})
]}).handle(args);
});
... ...