Skip to content

Instantly share code, notes, and snippets.

@JMPerez

JMPerez/sw.js Secret

Created May 2, 2022 08:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JMPerez/150629f57629f18272bd7e47ae1b7739 to your computer and use it in GitHub Desktop.
Save JMPerez/150629f57629f18272bd7e47ae1b7739 to your computer and use it in GitHub Desktop.
ServiceWorker usied on jmperezperez.com, JMPerez's blog
const CACHE_VERSION = 29;
let CURRENT_CACHE = 'main-v' + CACHE_VERSION;
const cacheFiles = [
'/',
'/about-me/',
'/projects/',
'/offline/'
];
self.addEventListener('activate', evt =>
evt.waitUntil(
caches.keys().then(cacheNames => {
return Promise.all(
cacheNames.map(cacheName => {
if (cacheName !== CURRENT_CACHE) {
return caches.delete(cacheName);
}
})
);
})
)
);
self.addEventListener('install', evt =>
evt.waitUntil(
caches.open(CURRENT_CACHE)
.then(cache => {
return cache.addAll(cacheFiles);
})
)
);
const fromNetwork = (request, timeout) =>
new Promise((fulfill, reject) => {
var timeoutId = setTimeout(reject, timeout);
fetch(request).then(response => {
clearTimeout(timeoutId);
fulfill(response);
update(request);
}, reject);
})
const fromCache = request =>
caches.open(CURRENT_CACHE).then(cache =>
cache.match(request).then(matching =>
matching || cache.match('/offline/')
)
);
const update = request =>
caches.open(CURRENT_CACHE).then(cache =>
fetch(request).then(response =>
cache.put(request, response)
)
);
self.addEventListener('fetch', evt => {
evt.respondWith(fromNetwork(evt.request, 10000).catch(
() => fromCache(evt.request)
));
evt.waitUntil(update(evt.request).catch(e => console.error(e)));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment