service worker we are facing cache issue

385 Views Asked by At

I am a fresher for service worker. I am trying to implement static and dynamic caching.

When I add the single file to the static cache request, it is taking all the files whatever I have. Currently, all the files are running from the service worker when I started from the offline mode. Please someone help me.

This is the code I have in index.html.

       self.addEventListener('install',function(event)
      {
      console.log('[service worker]Installing service 
       worker....',event);
      event.waitUntil(caches.open('static')
      .then(function(cache)
      {
          console.log('[Service Worker] Precaching App Shell');
          cache.addAll([
                       '/',
                       '/signin.html',
                       ]); 
    })
  )
});
1

There are 1 best solutions below

4
On

In Static caching some of the requests(pages) are cached(saved in Browser's local storage), it is generally done in install event of Service Worker. Whereas in Dynamic caching pages & files are cached whenever you request(fetch) for them hence, it makes use of fetch event of Service Worker.

So, in your install event when you add '/' in cache.addAll service worker adds all the files and resources needed to display '/' ie root directory.

Now, to make use of those cached files and to implement Dynamic Caching you'll need to implement something like this:

self.addEventListener('fetch', function (event) {

    event.respondWith(
      caches.match(event.request)       // if data has been cached already
        .then(function (response) {
          if (response) {
            return response;
          } else {              // else fetch from internet & cache in DYNAMIC cache
            return fetch(event.request)
              .then(function (res) {
                return caches.open(CACHE_DYNAMIC_NAME)
                  .then(function (cache) {
                    cache.put(event.request.url, res.clone());
                    return res;
                  })
              })
              .catch(function (err) {           //fallback mechanism
                return caches.open(CACHE_STATIC_NAME)
                  .then(function (cache) {
                    if (event.request.headers.get('accept').includes('text/html')) {
                      return cache.match('/offline.html');
                    }
                  });
              });
          }
        })
    );
});                  

NOTE: To avoid over crowding your local storage you might wanna implement some strategy before actually saving the file in storage.
For more info read this to learn more about strategies.