I am working on a React application that uses a Service Worker to cache resources and serve them in offline mode. My goal is to display a user location icon on a map even when the application is offline. Although the Service Worker caches the image, it does not serve it correctly when offline.
Issue with Offline Mode: When the application is offline, the Service Worker should serve the cached image localizacion_pin.png, but the image is not served correctly. The console logs show that the image request is intercepted by the Service Worker, but the image is not displayed.
fetch resoult
cache
What I have tried:
- Verified that the Service Worker caches the image during installation.
- Ensured the image URL is correct and matches the path in the Service Worker.
- Cleared the cache and reinstalled the Service Worker.
- Checked the Network tab to confirm that the Service Worker is intercepting requests and serving from the cache.
- Refactored the component to clear previous features from the vectorSource before adding the new location feature.
Also, it would be very helpful if someone could provide advice on how to show Bing Maps offline as well, because that is the next step I am going to try. Thank you in advance!
/* eslint-disable no-restricted-globals */
const CACHE_NAME = "offline-cache-v1";
const RESOURCES_TO_CACHE = [
'/',
'/index.html',
'/icons/localizacion_pin.png',
'/logo.gif',
'/logo.svg',
'/logo192.png',
'/logo512.png',
// Añade aquí otros recursos que desees cachear
];
self.addEventListener("install", event => {
console.log("Evento de instalación del Service Worker");
event.waitUntil(
caches.open(CACHE_NAME).then(cache => {
return cache.addAll(RESOURCES_TO_CACHE);
})
);
});
self.addEventListener('activate', event => {
console.log('Service Worker activado');
event.waitUntil(
caches.keys().then(cacheNames => {
return Promise.all(
cacheNames.map(cacheName => {
if (cacheName !== CACHE_NAME) {
console.log('Eliminando cache antiguo:', cacheName);
return caches.delete(cacheName);
}
})
);
})
);
});
self.addEventListener('fetch', event => {
console.log('Interceptando solicitud para:', event.request.url);
event.respondWith(
caches.match(event.request).then(cachedResponse => {
if (cachedResponse) {
console.log('Respuesta desde el cache:', event.request.url);
return cachedResponse;
}
return fetch(event.request).then(networkResponse => {
if (networkResponse && networkResponse.status === 200) {
caches.open(CACHE_NAME).then(cache => {
cache.put(event.request, networkResponse.clone());
});
}
return networkResponse;
}).catch(error => {
console.error('Error en la solicitud de red:', error);
if (event.request.destination === 'image') {
// Fallback para imágenes
return caches.match('/icons/localizacion_pin.png'); // Ajusta esto si necesitas un fallback específico para otras imágenes
} else if (event.request.destination === 'document') {
// Fallback para documentos (html)
return caches.match('/index.html');
}
});
})
);
});
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
const registerServiceWorker = async () => {
if ("serviceWorker" in navigator) {
try {
const registration = await navigator.serviceWorker.register("/serviceWorker.js", {
scope: "/",
});
if (registration.installing) {
console.log("Instalando el Service worker");
} else if (registration.waiting) {
console.log("Service worker instalado");
} else if (registration.active) {
console.log("Service worker activo");
}
} catch (error) {
console.error(`Falló el registro con el ${error}`);
}
}
};
registerServiceWorker();
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<App />
);
David Ortiz is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.