Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to cache all files of defined folder/path in service worker?

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?

like image 608
Mohd Yasin Avatar asked Oct 19 '17 13:10

Mohd Yasin


1 Answers

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.

like image 105
Jahongir Avatar answered Sep 19 '22 17:09

Jahongir