Search code examples
cachingbrowser-cacheservice-worker

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?


Solution

  • Runtime caching using Workbox sw.

    service-worker.js:

    importScripts('https://unpkg.com/[email protected]/build/importScripts/workbox-sw.dev.v0.0.2.js');
    importScripts('https://unpkg.com/[email protected]/build/importScripts/workbox-runtime-caching.prod.v1.3.0.js');
    importScripts('https://unpkg.com/[email protected]/build/importScripts/workbox-routing.prod.v1.3.0.js');
    
    const assetRoute = new workbox.routing.RegExpRoute({
        regExp: new RegExp('^http://localhost:8081/jobs/static/*'),
        handler: new workbox.runtimeCaching.CacheFirst()
    });
    
    const router = new workbox.routing.Router();
    //router.addFetchListener();
    router.registerRoutes({routes: [assetRoute]});
    router.setDefaultHandler({
        handler: new workbox.runtimeCaching.CacheFirst()
    });
    

    Script in my html file to load Servcie worker.

    <script>
        if ('serviceWorker' in navigator) {
            window.addEventListener('load', function() {
                navigator.serviceWorker.register('http://localhost:8081/jobs/static/service-worker.js?v=4').then(function(registration) {
                // Registration was successful
                console.log('ServiceWorker registration successful with scope: ', registration.scope);
            }, function(err) {
                // registration failed :(
                console.log('ServiceWorker registration failed: ', err);
                });
            });
        }
    </script>