Chapter 3. The CacheStorage API

At the end of Chapter 2 we took a giant step forward for the web—and for the Gotham Imperial Hotel—showing our user custom HTML content when she was offline instead of the browser’s error screen. Unfortunately, we also took two steps back and were only able to display a simple page with no images, no stylesheets, and none of the branding that makes a modern website worthy of the Gotham Imperial name.

Our goal for this chapter is for users visiting our site while offline to see the content of the index-offline.html file, including the images and stylesheets it contains (Figure 3-1). Go ahead and open it in your browser to see what it looks like (http://localhost:8443/index-offline.html).

Our cached offline home page
Figure 3-1. The page we would like to show our offline users

You can probably guess that in order to achieve this, we will have to catch requests that fail and return the alternate content:

self.addEventListener("fetch", function(event) {
  event.respondWith(
    fetch(event.request).catch(function() {
      return fetch("/index-offline.html");
    })
  );
});

Can you see the problem with this code?

It’s not a coding error, but an error in our logic. We are trying to fetch the offline file only when we know the user is offline. We need to fetch it while he is online, store it on the device, and serve it when he is offline.

The one piece of the puzzle that is still missing is this ...

Get Building Progressive Web Apps now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.