Soy nuevo en los trabajadores de servicio y las capacidades fuera de línea. Creé un trabajador de servicio simple para manejar las solicitudes de red y devolver una página html sin conexión cuando está desconectado. Esto fue creado siguiendo la guía de Google sobre PWA.
El problema es que el trabajador del servicio devuelve offline.html cuando solicita archivos javascript (no almacenados en caché). En su lugar, debería devolver un error de red o algo así. Aquí está el código:
const cacheName = 'offline-v1900'; //increment version to update cache // cache these files needed for offline use const appShellFiles = [ './offline.html', './css/bootstrap.min.css', './img/logo/logo.png', './js/jquery-3.5.1.min.js', './js/bootstrap.min.js', ]; self.addEventListener("fetch", (e) => { // We only want to call e.respondWith() if this is a navigation request // for an HTML page. // console.log(e.request.url); e.respondWith( (async () => { try { // First, try to use the navigation preload response if it's supported. const preloadResponse = await e.preloadResponse; if (preloadResponse) { // console.log('returning preload response'); return preloadResponse; } const cachedResponse = await caches.match(e.request); if (cachedResponse) { // console.log(`[Service Worker] Fetching cached resource: ${e.request.url}`); return cachedResponse; } // Always try the network first. const networkResponse = await fetch(e.request); return networkResponse; } catch (error) { // catch is only triggered if an exception is thrown, which is likely // due to a network error. // If fetch() returns a valid HTTP response with a response code in // the 4xx or 5xx range, the catch() will NOT be called. // console.log("Fetch failed; returning offline page instead.", error); const cachedResponse = await caches.match('offline.html'); return cachedResponse; } })() );Cuando estoy desconectado, abro una URL en mi sitio, carga la página desde el caché, pero no todos los activos se almacenan en caché sin conexión. Entonces, cuando se realiza una solicitud de red, digamos https://www.gstatic.com/firebasejs/9.1.3/firebase-app.js , la respuesta que obtengo es el html de la página offline.html. Esto rompe la página debido a errores de javascript.
En su lugar, debería devolver un error de red o algo así.
Creo que el código de muestra relevante es de https://googlechrome.github.io/samples/service-worker/custom-offline-page/
self.addEventListener('fetch', (event) => { // We only want to call event.respondWith() if this is a navigation request // for an HTML page. if (event.request.mode === 'navigate') { event.respondWith((async () => { try { // First, try to use the navigation preload response if it's supported. const preloadResponse = await event.preloadResponse; if (preloadResponse) { return preloadResponse; } const networkResponse = await fetch(event.request); return networkResponse; } catch (error) { // catch is only triggered if an exception is thrown, which is likely // due to a network error. // If fetch() returns a valid HTTP response with a response code in // the 4xx or 5xx range, the catch() will NOT be called. console.log('Fetch failed; returning offline page instead.', error); const cache = await caches.open(CACHE_NAME); const cachedResponse = await cache.match(OFFLINE_URL); return cachedResponse; } })()); } // If our if() condition is false, then this fetch handler won't intercept the // request. If there are any other fetch handlers registered, they will get a // chance to call event.respondWith(). If no fetch handlers call // event.respondWith(), the request will be handled by the browser as if there // were no service worker involvement. }); Específicamente, ese controlador de fetch verifica si event.request.mode === 'navigate' y solo devuelve HTML cuando está fuera de línea si ese es el caso. Eso es lo que se requiere para asegurarse de que no termine devolviendo HTML sin conexión para otros tipos de recursos.