Skip to content

Instantly share code, notes, and snippets.

@ptcane
Last active April 15, 2021 11:31
Show Gist options
  • Save ptcane/790f9118524f32fe2abf8557996e7a6a to your computer and use it in GitHub Desktop.
Save ptcane/790f9118524f32fe2abf8557996e7a6a to your computer and use it in GitHub Desktop.
PWA service worker for caching resources and specifying offline URL (MockStocks project)
// Modifying CACHE_VERSION will result in previous caches being deleted
// Add any routes and resources required for your offline page to CACHE_URLS
// Specify the page you want shown when offline (must be in CACHE_URLS) with OFFLINE_URL
const CACHE_VERSION = 'v1'
const CACHE_URLS = [
'/',
'/offline',
'pure.css',
'side-menu.css',
'style.css',
'ui.js',
'https://fonts.googleapis.com/css2?family=Quicksand&family=Share+Tech+Mono&display=swap',
'manifest.json',
'icons/apple-touch-icon.png',
'service-worker.js'
]
const OFFLINE_URL = '/offline'
// Section below adapted from
// https://googlechrome.github.io/samples/service-worker/basic/
// The install handler takes care of precaching the resources we always need
self.addEventListener('install', event => {
event.waitUntil(
caches.open(CACHE_VERSION)
.then(cache => cache.addAll(CACHE_URLS))
.then(self.skipWaiting())
)
})
// The activate handler takes care of cleaning up old caches.
self.addEventListener('activate', event => {
const currentCache = CACHE_VERSION;
event.waitUntil(
caches.keys().then(cacheNames => {
return cacheNames.filter(cacheName => !currentCache.includes(cacheName))
}).then(cachesToDelete => {
return Promise.all(cachesToDelete.map(cacheToDelete => {
return caches.delete(cacheToDelete);
}))
}).then(() => self.clients.claim())
)
})
// Section below adapted from https://web.dev/offline-cookbook/#cache-falling-back-to-network
self.addEventListener('fetch', function (event) {
event.respondWith(
// Try the cache
caches
.match(event.request)
.then(function (response) {
// Fall back to network
return response || fetch(event.request)
})
.catch(function () {
// If both fail, show a generic fallback:
return caches.match('/offline');
// However, in reality you'd have many different
// fallbacks, depending on URL and headers.
// Eg, a fallback silhouette image for avatars.
}),
)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment