Created
March 13, 2020 12:16
-
-
Save TimoBechtel/bad5dfdb0dd529812ee8cd53a9e5a608 to your computer and use it in GitHub Desktop.
Example service worker file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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