I don't want to preCache for all users but only for members. I want to do this to avoid unnecessary load on the server and unnecessarily caching for one-time visitors.
So when the visitor logs in, I send a message to the service worker. In the below snippet on the service worker, the 'Message Received' is logged in console. But the images are not cached. And there is no error message.
If I directly place precacheAndRoute(images)
below the const images = [....];
then the images are cached properly.
I am new to service workers. And any help is highly appreciated.
const images = [....];
addEventListener('message', (event) => {
if (event.data.type === 'cacheImages') {
console.log('Message Received');
precacheAndRoute(images);
}
});
The way precaching works in Workbox is by caching the files when the service worker is
installed
.You are calling
precacheAndRoute
inside an event in the SW, the SW is already installed, it won't execute the precacheAndRoute then.You might want to checkout the image cache recipe too.