Last active
October 31, 2019 11:26
-
-
Save janit/65affca09e97518d85bf40086aeabf31 to your computer and use it in GitHub Desktop.
Service Worker example for controlling what is cached - See https://malloc.fi/fix-duplicate-redirects-service-worker-caching
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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', '/']); | |
}); | |
} | |
self.addEventListener('fetch', function (event) { | |
// console.log('The service worker is serving the asset.'); | |
event.respondWith(checkResponse(event.request).catch(function () { | |
return returnFromCache(event.request) | |
} | |
)); | |
var storeInCache = true; | |
var dontCache = [ | |
'sw.js', | |
'/_redirect' | |
]; | |
dontCache.forEach(function (element) { | |
if (event.request.url.includes(element)) { | |
storeInCache = false; | |
} | |
}, this); | |
if (storeInCache) { | |
event.waitUntil(addToCache(event.request)); | |
} else { | |
console.log('do not cache ' + event.request.url); | |
} | |
}); | |
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 | |
} | |
}); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment