76 lines
2.0 KiB
JavaScript
76 lines
2.0 KiB
JavaScript
const CACHE_NAME = 'mims-library-v1';
|
|
const PRECACHE_URLS = [
|
|
'/',
|
|
'/offline.html',
|
|
'/favicon.svg',
|
|
'/manifest.json'
|
|
];
|
|
|
|
// Install: precache essential resources
|
|
self.addEventListener('install', (event) => {
|
|
event.waitUntil(
|
|
caches.open(CACHE_NAME).then((cache) => cache.addAll(PRECACHE_URLS))
|
|
);
|
|
self.skipWaiting();
|
|
});
|
|
|
|
// Activate: clean old caches
|
|
self.addEventListener('activate', (event) => {
|
|
event.waitUntil(
|
|
caches.keys().then((keys) =>
|
|
Promise.all(keys.filter((k) => k !== CACHE_NAME).map((k) => caches.delete(k)))
|
|
)
|
|
);
|
|
self.clients.claim();
|
|
});
|
|
|
|
// Fetch: tiered caching strategy
|
|
self.addEventListener('fetch', (event) => {
|
|
const { request } = event;
|
|
const url = new URL(request.url);
|
|
|
|
// Only handle same-origin
|
|
if (url.origin !== location.origin) return;
|
|
|
|
// Static assets: cache-first
|
|
if (/\.(css|js|jpg|jpeg|png|gif|svg|woff|woff2|ico)$/.test(url.pathname)) {
|
|
event.respondWith(
|
|
caches.match(request).then((cached) =>
|
|
cached || fetch(request).then((response) => {
|
|
const clone = response.clone();
|
|
caches.open(CACHE_NAME).then((cache) => cache.put(request, clone));
|
|
return response;
|
|
})
|
|
)
|
|
);
|
|
return;
|
|
}
|
|
|
|
// PDFs: network-first, cache on success
|
|
if (/\.pdf$/.test(url.pathname)) {
|
|
event.respondWith(
|
|
fetch(request)
|
|
.then((response) => {
|
|
const clone = response.clone();
|
|
caches.open(CACHE_NAME).then((cache) => cache.put(request, clone));
|
|
return response;
|
|
})
|
|
.catch(() => caches.match(request))
|
|
);
|
|
return;
|
|
}
|
|
|
|
// HTML pages: network-first with offline fallback
|
|
event.respondWith(
|
|
fetch(request)
|
|
.then((response) => {
|
|
const clone = response.clone();
|
|
caches.open(CACHE_NAME).then((cache) => cache.put(request, clone));
|
|
return response;
|
|
})
|
|
.catch(() =>
|
|
caches.match(request).then((cached) => cached || caches.match('/offline.html'))
|
|
)
|
|
);
|
|
});
|