From 416ccb07e7a006e679ddc86f93bcb30cdd7cac1b Mon Sep 17 00:00:00 2001 From: Luke Childs Date: Thu, 22 Sep 2016 19:26:29 +0100 Subject: [PATCH] Show how out of date stale pages are --- public/assets/enhancements.js | 14 +++++++++++++- public/assets/style.css | 7 +++++++ public/sw.js | 9 ++++++++- views/index.html | 1 + 4 files changed, 29 insertions(+), 2 deletions(-) diff --git a/public/assets/enhancements.js b/public/assets/enhancements.js index 459ac35..5a5c7bd 100644 --- a/public/assets/enhancements.js +++ b/public/assets/enhancements.js @@ -224,8 +224,20 @@ }; // Register service worker - if(supports.test(['serviceWorker'])) { + if(supports.test(['serviceWorker', 'querySelector', 'classList'])) { navigator.serviceWorker.register('/sw.js'); + DOMReady(function() { + if(window.cacheDate) { + var offlineMessage = create('div'); + offlineMessage.classList.add('cache-message'); + offlineMessage.innerText = '*There seems to be an issue connecting to the server. This is a cached version of this page from ' + window.cacheDate; + var main = find('main'); + if(main) { + doc.body.classList.add('no-connection'); + main.insertBefore(offlineMessage, main.firstChild); + } + } + }); } // Init favourite nodes diff --git a/public/assets/style.css b/public/assets/style.css index 454f1b8..03389f6 100644 --- a/public/assets/style.css +++ b/public/assets/style.css @@ -371,6 +371,13 @@ footer { font-size: 18px; } +/* Cache message */ +.cache-message { + font-size: 12px; + color: rgba(255, 255, 255, 0.9); + margin-bottom: 1rem; +} + /* Large desktop */ @media (min-width: 1230px) { pre { diff --git a/public/sw.js b/public/sw.js index 4a030e4..e6ce2f1 100644 --- a/public/sw.js +++ b/public/sw.js @@ -56,7 +56,14 @@ self.addEventListener('fetch', function(event) { .then(function(response) { if(requestUrl.pathname === '/') { caches.open(cacheName).then(function(cache) { - cache.put(event.request, response.clone()); + + // Modify the response html so we know when it was cached + response.clone().text().then(function(html) { + html = html.replace('window.cacheDate=false;', 'window.cacheDate="'+Date()+'";'); + var modifiedResponse = new Response(new Blob([html]), { headers: response.headers }); + cache.put(event.request, modifiedResponse); + }); + }); } diff --git a/views/index.html b/views/index.html index f580192..6a66f79 100644 --- a/views/index.html +++ b/views/index.html @@ -39,6 +39,7 @@ +