From 5b39b8a020ece3698b32b49d6af3afd1b9271c84 Mon Sep 17 00:00:00 2001 From: Luke Childs Date: Wed, 21 Sep 2016 23:51:50 +0100 Subject: [PATCH] Show cached offline page if no internet --- public/sw.js | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/public/sw.js b/public/sw.js index ab303ce..ef6128c 100644 --- a/public/sw.js +++ b/public/sw.js @@ -1,4 +1,5 @@ -var cacheName = 'top-explorer-cache-v1'; +var cacheName = 'top-explorer-cache-v1'; +var offlineUrl = '/no-connection'; // Install self.addEventListener('install', function(event) { @@ -8,6 +9,7 @@ self.addEventListener('install', function(event) { caches.open(cacheName) .then(function(cache) { return cache.addAll([ + offlineUrl, '/assets/style.css', '/assets/enhancements.js', '/assets/iconfont.woff', @@ -31,6 +33,20 @@ self.addEventListener('fetch', function(event) { checkCacheFirst(event); return; } + + // If we navigate to a page + if(event.request.mode === 'navigate') { + event.respondWith( + fetch(event.request) + + // and it fails + .catch(function() { + + // Show pretty offline page + return caches.match(offlineUrl); + }) + ); + } }); // Try cache first, if we don't have it make the request