Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const cacheName = 'storage';
- function signalTimeout(ms) {
- const controller = new AbortController();
- setTimeout(() => controller.abort(), ms);
- return controller.signal;
- }
- function log(msg) {
- console.log(msg);
- }
- self.addEventListener('fetch', e => {
- if(e.request.method != 'GET') return;
- e.respondWith(async function() {
- const url = new URL(e.request.url).pathname;
- const cache = await caches.match(e.request);
- if(cache) {
- try {
- const head = await fetch(url, {
- method: 'HEAD',
- signal: signalTimeout(7000)
- });
- const fetchedET = head.headers.get('last-modified');
- const cachedET = cache.headers.get('last-modified');
- if(fetchedET === cachedET) {
- log(`[${url}] Up to date, using cached`);
- return cache;
- }
- }
- catch(err) {
- const nw = err.name === 'AbortError' ? 'dogshit' : 'unavailable';
- log(`[${url}] Network is ${nw}, using cached`);
- return cache;
- }
- }
- try {
- const fetchedObject = await fetch(e.request);
- if(fetchedObject.ok) {
- const storage = await caches.open(cacheName);
- storage.put(e.request, fetchedObject.clone());
- log(`[${url}] New version, fetching and caching`);
- }
- return fetchedObject;
- }
- catch(err) {
- if(cache) return cache;
- throw err;
- }
- }());
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement