Skip to content

Instantly share code, notes, and snippets.

@nmiguelmoura
Last active May 15, 2019 09:37
Show Gist options
  • Save nmiguelmoura/dca8a8ff9c6c615f451cb7bf022c6f84 to your computer and use it in GitHub Desktop.
Save nmiguelmoura/dca8a8ff9c6c615f451cb7bf022c6f84 to your computer and use it in GitHub Desktop.
An exemple of a service worker that always tries to fetch results, fallbacking to cache only if theres a fetch error.
const CACHE_VERSION = 'cache_version_1';
self.addEventListener('install', (event) => {
console.log('service worker install');
if(!caches in self) {
return;
}
event.waitUntil(
caches.open(CACHE_VERSION)
.then(cache => {
return cache.addAll([
'/',
'/login/pt/'
]);
})
.catch(error => console.log(error))
);
});
self.addEventListener('activate', (event) => {
console.log('service worker activate');
event.waitUntil(
caches.keys()
.then(cacheKeys => {
return Promise.all(
cacheKeys.map(cacheKey => {
if(cacheKey !== CACHE_VERSION) {
return caches.delete(cacheKey);
}
})
);
})
);
});
self.addEventListener('fetch', (event) => {
console.log('Service worker fetching: ', event.request.method);
if(event.request.method !== 'POST') {
event.respondWith(
fetch(event.request)
.then(response => {
caches.open(CACHE_VERSION)
.then(cache => cache.put(event.request, response.clone()));
return response.clone();
})
.catch(() => {
return caches.match(event.request)
.then(response => {
return response || new Response('App offline');
})
})
)
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment