Skip to content

Instantly share code, notes, and snippets.

@TimoBechtel
Created March 13, 2020 12:16
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 TimoBechtel/bad5dfdb0dd529812ee8cd53a9e5a608 to your computer and use it in GitHub Desktop.
Save TimoBechtel/bad5dfdb0dd529812ee8cd53a9e5a608 to your computer and use it in GitHub Desktop.
Example service worker file
// https://timobechtel.de/111-challenge/create-a-pwa/
const cacheName = 'my-site-cache-v1';
const offline_page = '/offline.html';
const filesToCache = ['/', '/styles/main.css', '/script/main.js', offline_page];
self.addEventListener('install', function(event) {
event.waitUntil(
caches.open(cacheName).then(function(cache) {
return cache.addAll(filesToCache);
})
);
});
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request).then(function(response) {
if (response) {
return response;
}
return fetch(event.request).catch(function(error) {
return caches.match(offline_page).then(function(response) {
return response;
});
});
})
);
});
self.addEventListener('activate', function(event) {
event.waitUntil(
// delete old caches
caches.keys().then(function(cacheNames) {
return Promise.all(
cacheNames.map(function(foundCacheName) {
if (foundCacheName !== cacheName) {
return caches.delete(foundCacheName);
}
})
);
})
);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment