NextWks/app/static/sw.js

57 lines
1.6 KiB
JavaScript

// Next Workspace - Service Worker
// Cache name includes timestamp to force update on deploy
const CACHE_NAME = 'nextwks-v1';
const STATIC_ASSETS = [
'/',
'/static/manifest.json',
'/static/icons/icon-192.svg',
'/static/icons/icon-512.svg',
];
// Install: cache static assets
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open(CACHE_NAME).then((cache) => {
return cache.addAll(STATIC_ASSETS);
})
);
});
// Activate: clean old caches
self.addEventListener('activate', (event) => {
event.waitUntil(
caches.keys().then((keys) => {
return Promise.all(
keys
.filter((key) => key !== CACHE_NAME)
.map((key) => caches.delete(key))
);
})
);
});
// Fetch: serve from cache first, fall back to network
self.addEventListener('fetch', (event) => {
// Only handle GET requests
if (event.request.method !== 'GET') return;
// For navigation requests, always go to network
if (event.request.mode === 'navigate') {
event.respondWith(fetch(event.request).catch(() => caches.match('/')));
return;
}
// For static assets, try cache first
event.respondWith(
caches.match(event.request).then((cached) => {
return cached || fetch(event.request).then((response) => {
// Cache successful responses for static assets
if (response.status === 200 && event.request.url.includes('/static/')) {
const clone = response.clone();
caches.open(CACHE_NAME).then((cache) => cache.put(event.request, clone));
}
return response;
});
})
);
});