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).
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(){returnfetch("/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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access