Skip to content

Instantly share code, notes, and snippets.

@metastable
Forked from thangman22/register.js
Created November 3, 2020 06:08
Show Gist options
  • Select an option

  • Save metastable/bc61d56d5396b21e67e4659efa4e179d to your computer and use it in GitHub Desktop.

Select an option

Save metastable/bc61d56d5396b21e67e4659efa4e179d to your computer and use it in GitHub Desktop.
Workbox for Wordpress
async function addToCache(urls) {
const pageCache = await window.caches.open('page-cache');
await pageCache.addAll(urls);
}
// Check that service workers are registered
if ('serviceWorker' in navigator) {
// Use the window load event to keep the page load performant
window.addEventListener('load', () => {
addToCache(['/hello-world/', '/main-page/']);
navigator.serviceWorker.register('/sw.js');
});
}
importScripts("https://storage.googleapis.com/workbox-cdn/releases/3.0.0/workbox-sw.js")
workbox.setConfig({
debug: false
})
workbox.routing.registerRoute(
new RegExp('.*(?:googleapis|gstatic)\.com.*$'),
workbox.strategies.staleWhileRevalidate(),
)
workbox.routing.registerRoute(
new RegExp('.*(?:gravatar)\.com.*$'),
workbox.strategies.staleWhileRevalidate(),
)
workbox.routing.registerRoute(
new RegExp('.*\.js'),
workbox.strategies.staleWhileRevalidate({
cacheName: 'js-cache',
})
)
workbox.routing.registerRoute(
new RegExp('.*\.css'),
workbox.strategies.staleWhileRevalidate({
cacheName: 'css-cache',
})
)
workbox.routing.registerRoute(
new RegExp('.*\.woff2'),
workbox.strategies.staleWhileRevalidate({
cacheName: 'font-cache',
})
)
workbox.routing.registerRoute(
/\.(?:png|gif|jpg|jpeg|svg|ico)$/,
workbox.strategies.staleWhileRevalidate({
cacheName: 'image-cache',
})
)
workbox.routing.registerRoute(
new RegExp('^((?!wp-admin|wp-login).)*$'),
workbox.strategies.staleWhileRevalidate({
cacheName: 'page-cache',
plugins: [
new workbox.expiration.Plugin({
maxEntries: 10,
maxAgeSeconds: 7 * 24 * 60 * 60
})
]
})
)
workbox.routing.setCatchHandler(({ url, event, params }) => {
return caches.match('/offline/')
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment