Caching on this website did not work as expected especially when content updated. So, today I improved the service worker that comes with this blog.

This post is a follow up to this blog post.

First, I fixed an issue where the cache was not updated when the page was updated.

Deleting old cache

To do that, I added a function to the service worker that listens to the activate event and deletes old caches:

self.addEventListener('activate', function(event) {
  event.waitUntil(
    // delete old caches
    caches.keys().then(function(cacheNames) {
      return Promise.all(
        cacheNames.map(function(foundCacheName) {
          if (foundCacheName !== cacheName) {
            return caches.delete(foundCacheName);
          }
        })
      );
    })
  );
});

Always cache the last 5 blog posts

Next I wanted to always cache the last 5 blog post. For this I used liquid to get the last posts from jekyll:

[...]
const filesToCache = [
  '/',
  {%- for post in site.posts limit:5 -%}
  '{{post.url}}',
  {%- endfor -%}
];
[...]

Adding an offline notice page

At last, I added a page that is shown if the user tries to access a page that is not cached when being offline.

I created a page called offline.html and added it to the cache:

const offline_page = '/offline.html';
const filesToCache = [
  // all your files...
  offline_page
];

Now we can catch exceptions in our fetch function that occur when the user is offline and load the cached offline.html page:

self.addEventListener('fetch', function(event) {
  event.respondWith(
    caches.match(event.request).then(function(response) {
      if (response) {
        return response;
      }
      return fetch(event.request).catch(function(error) {
        return caches.match(offline_page).then(function(response) {
          return response;
        });
      });
    })
  );
});

You can find the generated service worker file for this blog here.