Skip to content

Instantly share code, notes, and snippets.

@jschopplich jschopplich/sw.js
Last active Aug 15, 2019

Embed
What would you like to do?
importScripts('https://storage.googleapis.com/workbox-cdn/releases/4.3.1/workbox-sw.js')
if (workbox) {
workbox.precaching.precacheAndRoute([])
workbox.routing.registerRoute(
// Common image types
new RegExp('\.(?:png|jpg|svg|webp)$'),
// Use a cache-first strategy
new workbox.strategies.CacheFirst({
cacheName: 'workbox-images-cache',
plugins: [
new workbox.expiration.Plugin({
maxEntries: 60,
maxAgeSeconds: 30 * 24 * 60 * 60, // 30 Days
// Remove cached images before purging other caches
purgeOnQuotaError: true
})
]
})
)
const ALLOWED_HOSTS = [
// Allow URLs from your domain
location.host
// Optionally add further domains, e.g. for cloud-optimized images
// 'cloudinary.com'
]
const DISALLOWED_FRAGMENTS = [
// Kirby’s API
'/api',
// Page drafts
'?token',
// The panel itself
'/panel'
]
const matchCallback = ({ url, event }) => {
return
// Ignore non-GET requests
event.request.method === 'GET'
// Continue if the URL's host is allowed to be cached
&& ALLOWED_HOSTS.includes(url.host)
// Cancel if any disallowed fragments exist
&& DISALLOWED_FRAGMENTS.some(el => url.pathname.includes(el)) === false
}
workbox.routing.registerRoute(
// Custom callback for handling a route
matchCallback,
// Use a network-first strategy
new workbox.strategies.NetworkFirst({
cacheName: 'workbox-pages-cache',
plugins: [
new workbox.expiration.Plugin({
maxEntries: 60,
maxAgeSeconds: 30 * 24 * 60 * 60 // 30 Days
})
]
})
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.