pinafore/templates/service-worker.js

85 lines
2.2 KiB
JavaScript
Raw Normal View History

2018-01-14 22:54:26 +00:00
const timestamp = '__timestamp__'
const ASSETS = `cache${timestamp}`
2018-01-06 23:51:25 +00:00
// `shell` is an array of all the files generated by webpack,
// `assets` is an array of everything in the `assets` directory
2018-01-14 22:54:26 +00:00
const to_cache = __shell__.concat(__assets__)
const cached = new Set(to_cache)
2018-01-06 23:51:25 +00:00
// `routes` is an array of `{ pattern: RegExp }` objects that
// match the pages in your app
2018-01-14 22:54:26 +00:00
const routes = __routes__
2018-01-06 23:51:25 +00:00
self.addEventListener('install', event => {
2018-01-14 22:54:26 +00:00
event.waitUntil(
caches
.open(ASSETS)
.then(cache => cache.addAll(to_cache))
.then(() => {
self.skipWaiting()
})
)
})
2018-01-06 23:51:25 +00:00
self.addEventListener('activate', event => {
2018-01-14 22:54:26 +00:00
event.waitUntil(
caches.keys().then(async keys => {
// delete old caches
for (const key of keys) {
if (key !== ASSETS) {
await caches.delete(key)
}
}
2018-01-06 23:51:25 +00:00
2018-01-14 22:54:26 +00:00
await self.clients.claim()
})
)
})
2018-01-06 23:51:25 +00:00
self.addEventListener('fetch', event => {
2018-01-14 22:54:26 +00:00
const url = new URL(event.request.url)
2018-01-06 23:51:25 +00:00
2018-01-14 22:54:26 +00:00
// don't try to handle e.g. data: URIs
if (!url.protocol.startsWith('http')) {
return
}
2018-01-06 23:51:25 +00:00
2018-01-14 22:54:26 +00:00
// always serve assets and webpack-generated files from cache
if (cached.has(url.pathname)) {
event.respondWith(caches.match(event.request))
return
}
2018-01-06 23:51:25 +00:00
2018-01-14 22:54:26 +00:00
// for pages, you might want to serve a shell `index.html` file,
// which Sapper has generated for you. It's not right for every
// app, but if it's right for yours then uncomment this section
2018-01-06 23:51:25 +00:00
2018-01-14 22:54:26 +00:00
if (url.origin === self.origin && routes.find(route => route.pattern.test(url.pathname))) {
event.respondWith(caches.match('/index.html'));
return;
}
2018-01-06 23:51:25 +00:00
2018-01-14 22:54:26 +00:00
// for everything else, try the network first, falling back to
// cache if the user is offline. (If the pages never change, you
// might prefer a cache-first approach to a network-first one.)
event.respondWith(
caches
.open(`offline${timestamp}`)
.then(async cache => {
try {
const response = await fetch(event.request)
cache.put(event.request, response.clone())
return response
} catch (err) {
const response = await cache.match(event.request)
if (response) {
return response
}
throw err
}
})
)
})