I have a problem with getting service worker to work
I tried a lot of solutions and nothing worked
What i'm trying to do is to cache the files for offline use
BTW this is the first time i work with service workers
main.js:
if ('serviceWorker' in navigator) {
navigator.serviceWorker
.register('/sw.js')
.catch(function(err) {
console.error(err);
});
}
sw.js:
const files = [
'/',
'/index.html',
'/restaurant.html',
'/css/styles.css',
'/js/dbhelper.js',
'/js/main.js',
'/js/restaurant_info.js',
'/data/restaurants.json',
'/img/1.jpg',
'/img/2.jpg',
'/img/3.jpg',
'/img/4.jpg',
'/img/5.jpg',
'/img/6.jpg',
'/img/7.jpg',
'/img/8.jpg',
'/img/9.jpg',
'/img/10.jpg'
];
self.addEventListener('install', function(e) {
e.waitUntil(
caches.open('v1').then(function(cache) {
return cache.addAll(files);
})
);
});
self.addEventListener('fetch', function(e) {
e.respondWith(
caches.match(e.request).then(function(response) {
if (response) {
console.log('Found ', e.request, ' in cache');
return response;
}
else {
console.log('Could not find ', e.request, ' in cache, FETCHING!');
return fetch(e.request)
.then(function(response) {
const clonedResponse = response.clone();
caches.open('v1').then(function(cache) {
cache.put(e.request, clonedResponse);
})
return response;
})
.catch(function(err) {
console.error(err);
});
}
})
);
});
These files were served using python -m http.server
