blog/src/service-worker.js

36 lines
873 B
JavaScript
Raw Normal View History

2018-01-26 18:56:01 +00:00
var CACHE = 'v3';
self.addEventListener('install', function() {
return self.skipWaiting();
})
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) {
2018-01-26 18:56:01 +00:00
return fetch(event.request)
.then(function(networkResponse) {
cache.put(event.request, networkResponse.clone());
return networkResponse;
})
.catch(function(err) {
console.log(err)
return caches.match(event.request);
2017-10-15 06:24:21 +00:00
});
2017-10-11 20:25:20 +00:00
});
}