aboutsummaryrefslogtreecommitdiff
path: root/static/js
diff options
context:
space:
mode:
authorChristine Dodrill <me@christine.website>2018-10-20 13:17:13 -0700
committerChristine Dodrill <me@christine.website>2018-10-20 13:24:18 -0700
commitdf2301f496ce0bd81bc8967fb27d49f7c76fe948 (patch)
tree0df2774761c4f5be5b9d3418a5aba0b5ebcc63df /static/js
parentcb2d716b38ca330b4d183a47ff9a8142fdf58c7f (diff)
downloadxesite-df2301f496ce0bd81bc8967fb27d49f7c76fe948.tar.xz
xesite-df2301f496ce0bd81bc8967fb27d49f7c76fe948.zip
static: support offline page service worker
Diffstat (limited to 'static/js')
-rwxr-xr-xstatic/js/pwabuilder-sw.js55
1 files changed, 55 insertions, 0 deletions
diff --git a/static/js/pwabuilder-sw.js b/static/js/pwabuilder-sw.js
new file mode 100755
index 0000000..4b3b1e2
--- /dev/null
+++ b/static/js/pwabuilder-sw.js
@@ -0,0 +1,55 @@
+//This is the service worker with the combined offline experience (Offline page + Offline copy of pages)
+
+//Install stage sets up the offline page in the cache and opens a new cache
+self.addEventListener('install', function(event) {
+ event.waitUntil(preLoad());
+});
+
+var preLoad = function(){
+ console.log('[PWA Builder] Install Event processing');
+ return caches.open('pwabuilder-offline').then(function(cache) {
+ console.log('[PWA Builder] Cached index and offline page during Install');
+ return cache.addAll(['/offline.html', '/index.html']);
+ });
+}
+
+self.addEventListener('fetch', function(event) {
+ console.log('[PWA Builder] The service worker is serving the asset.');
+ event.respondWith(checkResponse(event.request).catch(function() {
+ return returnFromCache(event.request)}
+ ));
+ event.waitUntil(addToCache(event.request));
+});
+
+var checkResponse = function(request){
+ return new Promise(function(fulfill, reject) {
+ fetch(request).then(function(response){
+ if(response.status !== 404) {
+ fulfill(response)
+ } else {
+ reject()
+ }
+ }, reject)
+ });
+};
+
+var addToCache = function(request){
+ return caches.open('pwabuilder-offline').then(function (cache) {
+ return fetch(request).then(function (response) {
+ console.log('[PWA Builder] add page to offline'+response.url)
+ return cache.put(request, response);
+ });
+ });
+};
+
+var returnFromCache = function(request){
+ return caches.open('pwabuilder-offline').then(function (cache) {
+ return cache.match(request).then(function (matching) {
+ if(!matching || matching.status == 404) {
+ return cache.match('offline.html')
+ } else {
+ return matching
+ }
+ });
+ });
+};