blog/src/service-worker.js

31 lines
842 B
JavaScript
Raw Normal View History

2017-10-15 07:35:38 +00:00
var CACHE = 'v2';
2017-10-11 20:25:20 +00:00
self.addEventListener('fetch', function(event) {
event.respondWith(fetchAndCache(event));
});
2017-10-15 07:18:49 +00:00
function cacheBust(request) {
var url = request.url;
if (url.indexOf(self.location.origin) >= 0) {
2017-10-15 07:35:38 +00:00
if (url[url.length - 1] !== '/' && (url.indexOf('.') < 0 || url.lastIndexOf('.') < self.location.origin.length)) {
2017-10-15 07:18:49 +00:00
url += `/`;
}
return `${url}?${Math.random()}`;
} else {
return request;
}
}
2017-10-11 20:25:20 +00:00
function fetchAndCache(event) {
return caches.open(CACHE).then(function (cache) {
2017-10-15 06:24:21 +00:00
return cache.match(event.request).then(response => {
2017-10-15 07:18:49 +00:00
var fetchResponse = fetch(cacheBust(event.request))
2017-10-15 06:24:21 +00:00
.then(function(networkResponse) {
cache.put(event.request, networkResponse.clone());
return networkResponse;
});
return response || fetchResponse;
});
2017-10-11 20:25:20 +00:00
});
}