diff --git a/web/index.html b/web/index.html index fb16f0f..9c39029 100644 --- a/web/index.html +++ b/web/index.html @@ -33,7 +33,25 @@ diff --git a/web/public/sw.js b/web/public/sw.js index 78dc714..a2fc8e6 100644 --- a/web/public/sw.js +++ b/web/public/sw.js @@ -1,16 +1,15 @@ /** * Service worker Météo Exam. - * - Cache les assets statiques (app shell) pour un démarrage hors ligne. - * - Les appels API passent en network-first : les données restent fraîches. + * + * Stratégie : + * - index.html : network-first (toujours la dernière version, pas de cache périmé). + * - Assets versionnés (hash dans le nom) : cache-first (jamais changés après build). + * - API / SSE : jamais caché. */ -const CACHE_NAME = 'meteo-exam-v2' -const STATIC_ASSETS = ['/', '/index.html', '/manifest.webmanifest'] +const CACHE_NAME = 'meteo-exam-v3' -self.addEventListener('install', (event) => { - event.waitUntil( - caches.open(CACHE_NAME).then((cache) => cache.addAll(STATIC_ASSETS)), - ) +self.addEventListener('install', () => { self.skipWaiting() }) @@ -27,13 +26,40 @@ self.addEventListener('fetch', (event) => { const { request } = event const url = new URL(request.url) - // API et flux SSE : toujours réseau, pas de cache. - if (url.pathname.startsWith('/api/')) return + // API et flux SSE : réseau uniquement. + if (url.pathname.startsWith('/api/') || url.pathname.startsWith('/stream')) return - // Assets statiques : cache d'abord, réseau en secours. - if (request.method === 'GET' && (url.origin === self.location.origin || url.hostname === 'localhost')) { + // Seulement les requêtes same-origin. + if (url.origin !== self.location.origin) return + + // index.html (et racine) : network-first pour éviter le cache périmé. + if (url.pathname === '/' || url.pathname === '/index.html') { event.respondWith( - caches.match(request).then((cached) => cached ?? fetch(request).catch(() => caches.match('/index.html'))), + 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 + } + + // Assets versionnés (hash dans le nom) : cache-first. + if (request.method === 'GET') { + event.respondWith( + caches.match(request).then( + (cached) => + cached ?? + fetch(request).then((response) => { + if (response.ok) { + const clone = response.clone() + caches.open(CACHE_NAME).then((cache) => cache.put(request, clone)) + } + return response + }), + ), ) } })