Sid
Sid

Reputation: 1014

How to cache a React app with service workers

Im just wondering how to handle this. I want to have my whole app cached. Im have tried something like this which doesnt seem to work

self.addEventListener('install',(e)=>{
  console.log('installed');

})

self.addEventListener('activate',(e)=>{
  console.log('activated');
  self.skipWaiting();
})

self.addEventListener('fetch',(e)=>{
  e.respondWith(
    fetch(e.request)
      .then(res=>{
        const resClone = res.clone();
        caches.open(cacheName).then(cache=>{
          cache.put(e.request, resClone);
        })
        return res;

      }).catch(err => {
        console.log('no connection');
        caches.match(e.request).then(res => { return res })
      })
  )
})

Does anyone know how to approach this?

Upvotes: 0

Views: 3010

Answers (2)

Mehran Zahiroddini
Mehran Zahiroddini

Reputation: 61

This works for me,

self.addEventListener("fetch", function(event) {
  event.respondWith(
    caches.match(event.request).then(function(response) {
      if (response) {
        return response;
      } else {
        return fetch(event.request)
          .then(function(res) {
            return caches.open(CACHE_NAME).then(function(cache) {
              cache.put(event.request.url, res.clone());
              return res;
            });
          })
         
      }
    })
  );
});

This tells the service worker to read from cache first and then network if there is no response from cache. One thing to keep in mind, this will not check for any updates made to the files. If you change your react code, the service worker will load the previous files it has in cache.

To solve this you can use workbox's staleWhileRevalidate which updates the cache whenever there is network connection.

A less convenient solution would be to delete the cache on service worker activation:

self.addEventListener('activate', function(event) {
  event.waitUntil(
    caches.keys()
    .then(function(keyList) {
      return Promise.all(keyList.map(function(key) {
        return caches.delete(key);

      }));
    })
  );
  return self.clients.claim();
});

Whenever a new service worker is installed the cache is removed and a new one is created.

Upvotes: 0

Gayatri Dipali
Gayatri Dipali

Reputation: 1283

Like one childish way would be to view the page source and check what js, css files are being used by react and cache them manually.

This will not work in production, you will have to manually check the files in the build directory and update the service-worker

Or a better and sensible way of doing it would be to use workbox (a npm package from google) which is going to handle all this clutter

Upvotes: 1

Related Questions