I'm facing some challenges while trying to set up a service worker for my website.
My goal is to only cache css/js/fonts and specific images/svg files, without caching the HTML since it's constantly being updated every minute.
Although it seems to be partially working, I encountered issues when testing on my smartphone where I continuously receive the "Add to homescreen" notification even after adding it. Additionally, the Add button is not appearing in the Chrome Dev app.
Furthermore, Lighthouse has identified the following errors:
"Does not respond with a 200 when offline"
"User will not be prompted to Install the Web App, Failures: Manifest start_url is not cached by a Service Worker."
Currently, my sw.js file looks like this. I have commented out the fetch part as it was caching the HTML and causing issues with Cookies.
Is there a simple Service Worker template available that I can utilize?
const PRECACHE = 'app-name';
const RUNTIME = 'runtime';
// List of local resources to always be cached.
const PRECACHE_URLS = [
'/css/file.css',
'/js/file.js',
'/images/logo.png',
'/fonts/roboto/Roboto-Regular.woff2'
]
// Install handler for precaching necessary resources.
self.addEventListener('install', event => {
event.waitUntil(
caches.open(PRECACHE)
.then(cache => cache.addAll(PRECACHE_URLS))
.then(self.skipWaiting())
);
});
// Activate handler for cleaning up old caches.
self.addEventListener('activate', event => {
const currentCaches = [PRECACHE, RUNTIME];
event.waitUntil(
caches.keys().then(cacheNames => {
return cacheNames.filter(cacheName => !currentCaches.includes(cacheName));
}).then(cachesToDelete => {
return Promise.all(cachesToDelete.map(cacheToDelete => {
return caches.delete(cacheToDelete);
}));
}).then(() => self.clients.claim())
);
});