My first code is:
const FALLBACK_HTML_URL = '/offline.html';
let urlHandler = new NetworkFirst({
cacheName: 'html'
});
registerRoute(
({request}) => true,
({event}) => {
return urlHandler.handle({event})
.then((response) => {
return response || caches.match(FALLBACK_HTML_URL);
})
.catch(() => caches.match(FALLBACK_HTML_URL));
}
);
So when I install the PWA and run it in offline mode, the result is: This site can’t be reached
So I changed the NetworkFirst to CacheFirst. Same result: This site can’t be reached
I have two problems:
/offline.html.I fixed the second one with (Although I'm not sure if it is an appropriate way):
const CACHE_NAME = 'offline-html';
self.addEventListener('install', (event) => {
event.waitUntil((async () => {
const cache = await caches.open(CACHE_NAME);
await cache.add(new Request(FALLBACK_HTML_URL, {cache: 'reload'}));
})());
});
self.addEventListener('activate', (event) => {
event.waitUntil((async () => {
console.log(self.registration)
if ('navigationPreload' in self.registration) {
await navigationPreload.enable();
}
})());
});
self.addEventListener('fetch', (event) => {
if (event.request.mode === 'navigate') {
event.respondWith((async () => {
try {
const preloadResponse = await event.preloadResponse;
if (preloadResponse) {
return preloadResponse;
}
return await fetch(event.request);
} catch (error) {
const cache = await caches.open(CACHE_NAME);
return await cache.match(FALLBACK_HTML_URL);
}
})());
}
});
How can I load the pages that are cached in offline-mode? And if the cache is empty to load the page offline.html in offline-mode? And when NOT in offline-mode to load from the server?