I’m starting to implement a service worker in my React app to turn it into a Progressive Web App (PWA). My goal is to ensure the PWA is fully functional and all pages are available offline after the user presses the install button on the top right corner of the app.
However, I’m encountering several issues and have some questions about PWAs that I couldn’t find clear answers to online.
-
The ‘install’ event is triggered during the first page load, not when the ‘install’ button is pressed. Is there a specific event related to the installation process initiated by the user pressing the ‘install’ button? Pre-downloading every page during the initial load can be a lengthy process and may not be desirable for all users.
-
Since my app is built with React, it involves complex fetching processes with dynamic files. For instance, when I land on the homepage, caching all the resources needed for another page like the library page is challenging.
Here is the current state of my service worker code. It’s not very advanced yet, but I hope it helps to illustrate the issues I’m facing:
const CACHE_NAME = 'static-cache-v1';
const FILES_TO_CACHE = [
'/',
'/index.html',
'/css/style.css',
'/js/app.js',
'/logo.png',
'/logo.ico',
'/logo192.png',
'/logo512.png',
'/music.mp3',
'/processor.js',
'/_redirects',
];
const ROUTES_TO_CACHE = [
'/dashboard'
'/library',
'/settings',
]
self.addEventListener('install', (evt) => {
console.log('[ServiceWorker] Installl');
return evt.waitUntil((async () => {
console.log('[ServiceWorker] weird');
})());
});
self.addEventListener('activate', function (event)
{
event.waitUntil(self.clients.claim());
});
self.addEventListener('fetch', (evt) => {
console.log('[ServiceWorker] Fetch', evt.request.url);
evt.respondWith((async () => {
const cache = await caches.open(CACHE_NAME);
console.log('[cache]', await cache.keys());
let cachedResponse = await cache.match(evt.request);
if (cachedResponse !== undefined) {
console.log('[ServiceWorker] Found in Cache', evt.request.url);
fetch(evt.request).then((response) => {
cache.put(evt.request, response.clone());
});
return cachedResponse;
}
console.log('[ServiceWorker] Not Found in Cache', evt.request.url);
const fetched = await fetch(evt.request);
cache.put(evt.request, fetched.clone());
return fetched;
})());
});
Marco is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.