In service worker, I can define array of resource those are being cached during service worker get started mentioned below:
self.addEventListener('install', event => {
event.waitUntil(caches.open('static-${version}')
.then(cache => cache.addAll([
'/styles.css',
'/script.js'
]))
);
});
How can I define a path/directory in service worker, so that instead of writing all files name, service worker pick all files from given path/directory and add all in cache?
Yes you can. I have also such kind of problem and I find cool solution using performance
. Here is my sw.js
:
const KEY = 'key';
self.addEventListener('install', (event) => {
event.waitUntil(self.skipWaiting());
});
self.addEventListener('message', (event) => {
if (event.data.type === 'CACHE_URLS') {
event.waitUntil(
caches.open(KEY)
.then( (cache) => {
return cache.addAll(event.data.payload);
})
);
}
});
Here is my main.js
:
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js', { scope: '/' })
.then((registration) => {
const data = {
type: 'CACHE_URLS',
payload: [
location.href,
...performance.getEntriesByType('resource').map((r) => r.name)
]
};
registration.installing.postMessage(data);
})
.catch((err) => console.log('SW registration FAIL:', err));
}
By this you can also add some filter which will cache specific path.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With