hubl/src/sw.js
Jean-Baptiste Pasquier 37a0c62ccf fix: sw
2020-10-28 17:38:54 +01:00

112 lines
3.5 KiB
JavaScript

const CACHE_NAME = 'hubl-store-dev';
self.addEventListener('install', function (e) {
self.skipWaiting();
e.waitUntil(
caches.open(CACHE_NAME).then(function (cache) {
return cache.addAll([
'/locales/es.json',
'/locales/fr.json',
'/scripts/index.js',
'/syles/index.css',
'/index.html',
'/'
]);
})
);
});
self.addEventListener('activate', function (e) {
// invalidate older versions
e.waitUntil(
caches.keys()
.then(function (keyList) {
return Promise.all(keyList.map(function (key) {
if (key !== CACHE_NAME && key !== (CACHE_NAME + "-cdn") && key !== (CACHE_NAME + "-api")) {
return caches.delete(key);
}
}));
}));
self.clients.claim();
});
self.addEventListener('fetch', function (event) {
let requestURL = new URL(event.request.url);
if (requestURL.origin == location.origin) {
// Static asset, cache then network
event.respondWith(
caches.open(CACHE_NAME).then(function (cache) {
return cache.match(event.request).then(function (response) {
var fetchPromise = fetch(event.request).then(function (networkResponse) {
cache.put(event.request, networkResponse.clone());
return networkResponse;
});
return response || fetchPromise;
});
}),
);
} else {
if (
event.request.method == 'POST' ||
event.request.method == 'PUT'
) {
// disabled: lead to cors errors
// // POST/PUT to api, rewrite the cache
// event.respondWith(
// caches.open(CACHE_NAME + '-api').then(function (cache) {
// return fetch(event.request).then(function (response) {
// cache.put(event.request, response.clone());
// return response;
// })
// }));
// api: no cache
event.respondWith(fetch(event.request));
} else if (
/matomo/.test(requestURL.origin) ||
/sentry/.test(requestURL.origin) ||
/jabber/.test(requestURL.origin) ||
/xmpp/.test(requestURL.origin)
) {
// analytics, always distant
event.respondWith(fetch(event.request));
} else {
if (
/unpkg/.test(requestURL.origin) ||
/jspm/.test(requestURL.origin) ||
/jsdeliver/.test(requestURL.origin) ||
/cdn/.test(requestURL.origin) ||
/googleapis/.test(requestURL.origin)
) {
// cdn: cache then network
event.respondWith(
caches.open(CACHE_NAME + '-cdn').then(function (cache) {
return cache.match(event.request).then(function (response) {
var fetchPromise = fetch(event.request).then(function (networkResponse) {
cache.put(event.request, networkResponse.clone());
return networkResponse;
});
return response || fetchPromise;
});
}),
);
} else {
// disabled: lead to cors errors
// // api: distant then cache
// event.respondWith(
// fetch(event.request)
// .then((response) => {
// caches.open(CACHE_NAME + '-api').then(function (cache) {
// cache.put(event.request, response.clone());
// return response;
// });
// })
// .catch(() => {
// return caches.match(event.request);
// })
// );
// api: no cache
event.respondWith(fetch(event.request));
}
}
}
});