67 lines
1.9 KiB
JavaScript
67 lines
1.9 KiB
JavaScript
self.importScripts('https://storage.googleapis.com/workbox-cdn/releases/6.5.4/workbox-sw.js');
|
|
|
|
// This will trigger the importScripts() for workbox.strategies and its dependencies
|
|
// so that it can be used in the event handlers
|
|
// https://developer.chrome.com/docs/workbox/modules/workbox-sw/#avoid-async-imports
|
|
workbox.loadModule('workbox-strategies');
|
|
workbox.loadModule('workbox-expiration');
|
|
workbox.loadModule('workbox-routing');
|
|
|
|
const cacheName = 'my-cache';
|
|
|
|
self.addEventListener('install', function () {
|
|
self.skipWaiting();
|
|
});
|
|
|
|
self.addEventListener('fetch', (event) => {
|
|
const { request } = event;
|
|
const { pathname } = new URL(event.request.url);
|
|
|
|
const createCacheFirstStrategy = ({ items, maxAgeSeconds, maxEntries }) => {
|
|
items.map((item) => {
|
|
// if modify method, fetch fresh data:
|
|
if (event.request.method !== 'GET') {
|
|
caches.delete(item);
|
|
} else {
|
|
event.respondWith(
|
|
new workbox.strategies.CacheFirst({
|
|
cacheName,
|
|
plugins: [
|
|
// use both: time restrictions and max entries
|
|
new workbox.expiration.ExpirationPlugin({
|
|
maxAgeSeconds,
|
|
maxEntries,
|
|
}),
|
|
],
|
|
}).handle({ event, request })
|
|
);
|
|
}
|
|
});
|
|
};
|
|
|
|
createCacheFirstStrategy({
|
|
items: ['/', '/unlimited'],
|
|
maxAgeSeconds: 60,
|
|
maxEntries: 15,
|
|
});
|
|
|
|
// optional: if you want to have a way to bust all caches quickly
|
|
if (pathname.includes('/refresh')) {
|
|
caches.keys().then((names) => names.map((name) => caches.delete(name)));
|
|
} else {
|
|
return;
|
|
}
|
|
});
|
|
|
|
// workbox.routing.registerRoute(
|
|
// ({ request }) => request.destination === '/',
|
|
// new workbox.strategies.CacheFirst({
|
|
// cacheName: 'my-cache',
|
|
// plugins: [
|
|
// new workbox.expiration.ExpirationPlugin({
|
|
// maxAgeSeconds: 60, // Время кэширования в секундах
|
|
// }),
|
|
// ],
|
|
// })
|
|
// );
|