When I test the following code and I go to the cache storage of the chrome devtools it is empty. It worked at a moment and after changing the cacheName
at a moment it stopped, not sure if it is related.
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker
.register('sw_cached_pages.js')
.then(reg => console.log('Service Worker: Registered (Pages)'))
.catch(err => console.log(`Service Worker: Error: ${err}`));
});
}
And here is the SW itself:
const cacheName = '00001';
const cacheAssets = [
'accueil.php',
'js/accueil.js',
'inc/Headers.php',
'inc/footer.php'
];
// Call Install Event
self.addEventListener('install', e => {
console.log('Service Worker: Installed');
e.waitUntil(
caches
.open(cacheName)
.then(cache => {
console.log(cache)
console.log('Service Worker: Caching Files', cache);
cache.addAll(cacheAssets);
})
.then(() => self.skipWaiting())
);
});
// Call Activate Event
self.addEventListener('activate', e => {
console.log('Service Worker: Activated');
// Remove unwanted caches
e.waitUntil(
caches.keys().then(cacheNames => {
return Promise.all(
cacheNames.map(cache => {
if (cache !== cacheName) {
console.log('Service Worker: Clearing Old Cache');
return caches.delete(cache);
}
})
);
})
);
});
// Call Fetch Event
self.addEventListener('fetch', e => {
console.log('Service Worker: Fetching');
e.respondWith(fetch(e.request).catch(() => caches.match(e.request)));
});
Maybe the reason is that you have "Disable cache" checked in your browser's DevTools? That was the reason for a similar problem that I had.