diff --git a/internal/web/components/layout.templ b/internal/web/components/layout.templ index 0a2febc..f85ceb9 100644 --- a/internal/web/components/layout.templ +++ b/internal/web/components/layout.templ @@ -260,9 +260,7 @@ templ Layout(data *LayoutData, content templ.Component) { - if data.IsAuthenticated { - - } + { event.waitUntil( - caches.open(CACHE_NAME).then((cache) => cache.addAll(urlsToCache)), + caches.open(CACHE_NAME).then((cache) => cache.addAll(STATIC_ASSETS)), ); + // Activate immediately instead of waiting + self.skipWaiting(); }); -// Fetch from cache, fallback to network -self.addEventListener("fetch", (event) => { - event.respondWith( - caches.match(event.request).then((response) => { - // Cache hit - return response - if (response) { - return response; - } - return fetch(event.request); - }), +// Clean up old caches on activate +self.addEventListener("activate", (event) => { + event.waitUntil( + caches + .keys() + .then((cacheNames) => + Promise.all( + cacheNames + .filter((name) => name !== CACHE_NAME) + .map((name) => caches.delete(name)), + ), + ) + .then(() => self.clients.claim()), ); }); -// Update service worker -self.addEventListener("activate", (event) => { - const cacheWhitelist = [CACHE_NAME]; - event.waitUntil( - caches.keys().then((cacheNames) => { - return Promise.all( - cacheNames.map((cacheName) => { - if (cacheWhitelist.indexOf(cacheName) === -1) { - return caches.delete(cacheName); +// Fetch strategy: +// - Navigation requests (HTML pages): network-first with no cache fallback +// - Static assets: stale-while-revalidate +// - API/other: network only (pass through) +self.addEventListener("fetch", (event) => { + const url = new URL(event.request.url); + + // Only handle same-origin requests + if (url.origin !== self.location.origin) return; + + // Navigation requests (HTML pages): always go to network + // This ensures authenticated pages always get the latest head scripts + if (event.request.mode === "navigate") { + event.respondWith(fetch(event.request)); + return; + } + + // Static assets: stale-while-revalidate + if (url.pathname.startsWith("/static/")) { + event.respondWith( + caches.match(event.request).then((cached) => { + const fetchPromise = fetch(event.request).then((response) => { + if (response.ok) { + const clone = response.clone(); + caches.open(CACHE_NAME).then((cache) => cache.put(event.request, clone)); } - }), - ); - }), - ); + return response; + }); + return cached || fetchPromise; + }), + ); + return; + } + + // Everything else (API calls, etc.): network only });