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) {
    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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.