I'm using Nodejs and EJs as my templating engine for Node. I'm new to PWA and I want to create a Progressive Web Application and want to cache all of my ejs template files in the browser Cache. How can I do this? Is it going to work offline or not? I have tried to do this and service worker is successfully registered. Its also caching the files but when I'm running it in offline mode, its automatically deleting the cache while fetching. Can someone help me with this? I am running it on localhost:5000 from node server.
Directory Structure
App/
- css/
- images/
- res/
- sw1.js
- uploads/
- views/
-partials/
-footer.ejs
-index.ejs
-login.ejs
footer.ejs file
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('./sw1.js')
.then(() => console.log('Service worker Registered'))
.catch((error) => console.log('some error occurred',error));
}
sw1.js file
var cacheName = 'app-cache';
self.addEventListener('install', function(event) {
event.waitUntil(
caches.open(cacheName).then(function(cache) {
return cache.addAll([./css/main.css', './views/login.ejs', '/']);
})
);
console.log('Service Worker Installed');
});
self.addEventListener('activate', function(e) {
console.log('[Service Worker] Activate');
e.waitUntil(
caches.keys().then(function(keyList) {
return Promise.all(
keyList.map(function(key) {
if (key != cacheName) {
console.log('Removing old cache', key);
return caches.delete(key);
}
})
);
})
);
});
self.addEventListener("fetch", function(event){
if(event.request.url.startsWith("http://localhost:5000/")){
console.log("[Service Worker] Fetch", event.request.url);
caches.open(cacheName).then(function(cache){
return fetch(event.request).then(function(response){
cache.put(event.request, response.clone());
return response;
})
})
}
else{
event.respondWith(
caches.match(event.request).then(function(response){
return response || fetch(event.request);
})
);
}
});