Skip to content

Instantly share code, notes, and snippets.

@thangman22
Created April 1, 2018 07:21
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save thangman22/8e88d2683f8dad3664761e6bd25b4329 to your computer and use it in GitHub Desktop.
Save thangman22/8e88d2683f8dad3664761e6bd25b4329 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/')
})
@ErfanMHDi
Copy link

ErfanMHDi commented Jul 4, 2021

hello @thangman22,
Thanks for great snippets, it helps a lot!
i just have a question about offline page fallback.
Can you take a look at the code i'm using and give me a hint on what is it that im doing wrong ?

self.addEventListener('install', (event) => {
	const urls = [
		'/wp-assets/universal/offline/index.html',
		'/wp-assets/universal/offline/style.css',
		'/wp-assets/universal/fonts/fonts.css',
		'/wp-assets/universal/fonts/MiConSet/eot/MiConSet.eot',
		'/wp-assets/universal/fonts/MiConSet/svg/MiConSet.svg',
		'/wp-assets/universal/fonts/MiConSet/ttf/MiConSet.ttf',
		'/wp-assets/universal/fonts/MiConSet/woff/MiConSet.woff',
		'/wp-assets/universal/fonts/MiConSet/woff2/MiConSet.woff2'
	];
	event.waitUntil(caches.open('Initiate').then((cache) => cache.addAll(urls)));
});

workbox.routing.setCatchHandler(({ url, event, params }) => {
	return caches.match('/wp-assets/universal/offline/', {cacheName: 'Initiate'})
})

i just want to preCache some font, css and html of offline page
and serve them from cache when there is no network.

@ErfanMHDi
Copy link

when internet is offline, it's loading my offline page instead of browser page for urls and files that has been cached into service worker but from urls that has been excluded from service worker it returns the browser "no internet connection" Error Page.

for example for this link : www.example.com/checkout/

workbox.routing.registerRoute(
	({request, url}) => 
		request.mode === 'navigate'  &&
		!url.pathname.match(/^\/(wp-admin|wp-login|wp-json|wp-includes|wp-content|preview=true|search|bag|checkout|account)/) &&
		!url.href.match(/\?.+=.*/g),
		
		
	new workbox.strategies.StaleWhileRevalidate({
		cacheName: 'Pages',
		plugins: [
			new workbox.expiration.ExpirationPlugin({
				maxEntries: 25,
				maxAgeSeconds: 30 * 24 * 60 * 60 // 30 Days
			}),
			new workbox.cacheableResponse.CacheableResponsePlugin({
				statuses: [0, 200],
			}),
		]
	})
)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment