diff --git a/brutaldon/static/js/pwabuilder-sw.js b/brutaldon/static/js/pwabuilder-sw.js new file mode 100644 index 0000000..ba84f32 --- /dev/null +++ b/brutaldon/static/js/pwabuilder-sw.js @@ -0,0 +1,34 @@ +//This is the "Offline page" service worker + +//Install stage sets up the offline page in the cache and opens a new cache +self.addEventListener('install', function(event) { + var offlinePage = new Request('offline.html'); + event.waitUntil( + fetch(offlinePage).then(function(response) { + return caches.open('pwabuilder-offline').then(function(cache) { + console.log('[PWA Builder] Cached offline page during Install'+ response.url); + return cache.put(offlinePage, response); + }); + })); +}); + +//If any fetch fails, it will show the offline page. +//Maybe this should be limited to HTML documents? +self.addEventListener('fetch', function(event) { + event.respondWith( + fetch(event.request).catch(function(error) { + console.error( '[PWA Builder] Network request Failed. Serving offline page ' + error ); + return caches.open('pwabuilder-offline').then(function(cache) { + return cache.match('/static/offline.html'); + }); + } + )); +}); + +//This is a event that can be fired from your page to tell the SW to update the offline page +self.addEventListener('refreshOffline', function(response) { + return caches.open('pwabuilder-offline').then(function(cache) { + console.log('[PWA Builder] Offline page updated from refreshOffline event: '+ response.url); + return cache.put(offlinePage, response); + }); +}); diff --git a/brutaldon/static/offline.html b/brutaldon/static/offline.html new file mode 100644 index 0000000..ddc3b7c --- /dev/null +++ b/brutaldon/static/offline.html @@ -0,0 +1,13 @@ + +
++ Your page request will be fulfilled the next time you are online. + We don't seem to have this particular page in the cache for you. + Terribly sorry. +
+ + diff --git a/brutaldon/templates/base.html b/brutaldon/templates/base.html index bb3fba3..8f1d5a6 100644 --- a/brutaldon/templates/base.html +++ b/brutaldon/templates/base.html @@ -217,6 +217,17 @@ { $(".attachments").photobox('a', { history: true }); }); + if (navigator.serviceWorker.controller) { + console.log('[PWA Builder] active service worker found, no need to register') + } else { + + //Register the ServiceWorker + navigator.serviceWorker.register('{% static "js/pwabuilder-sw.js" %}', { + scope: './' + }).then(function(reg) { + console.log('Service worker has been registered for scope:'+ reg.scope); + }); + } {% block page_scripts_inline %} {% endblock %}