Asim K T
Asim K T

Reputation: 18144

Service worker: check cached resources are up-to-date or latest

I've sw.js code like:

self.addEventListener('install', e => {
  e.waitUntil(
    caches.open('cache').then(cache => {
      return cache.addAll([
        '/',
        '/index.html',
        '/styles/main.css',
        '/scripts/main.min.js'
      ])
      .then(() => self.skipWaiting());
    })
  )
});

self.addEventListener('activate',  event => {
  event.waitUntil(self.clients.claim());
});

self.addEventListener('fetch', event => {
  event.respondWith(
    caches.match(event.request).then(response => {
      return response || fetch(event.request);
    })
  );
});

I've updated the index.html file recently, but the file isn't reflected the site. It's still showing the old content of index.html.

Now, How can I make sure app will be serving the latest code if file's changed on the server?

I've been seeing some related answers (like update and refresh), but please tell me what's going on each part of the answer.

Upvotes: 0

Views: 1095

Answers (1)

Jeff Posnick
Jeff Posnick

Reputation: 56044

You have two options:

  1. Switch from your current cache-first strategy in your fetch handler to a strategy like stale-while-revalidate.
  2. Use a build-time tool to generate a service worker that changes each time one of your local resources changes, which will trigger the install and activate handlers, giving them a chance to update your users' caches with the latest copies of your assets. These tools work by generating hashes of each local file and inlining those hashes into the generated service worker script.

Option 2. is more efficient, because your users will only have to make requests for your assets when something actually changes, as opposed to when using a stale-while-revalidate strategy, which requires firing off a "revalidate" request in the background each time your fetch handler is invoked. Option 2. does require a bit more work, though, because you need to incorporate a step into your build process to generate your service worker for you.

If you go the option 2. route, there are a few different build tools that I know about:

Upvotes: 2

Related Questions