Skip to content

Instantly share code, notes, and snippets.

@ankitarora05
Last active July 30, 2022 23:28
Show Gist options
  • Save ankitarora05/dda5cf6bad1997e9015aa960b50b033c to your computer and use it in GitHub Desktop.
Save ankitarora05/dda5cf6bad1997e9015aa960b50b033c to your computer and use it in GitHub Desktop.
Automatically detect and update new PWA Workbox builds in nuxt.js
plugins: [{src: '@/plugins/pwa-update.js', mode: 'client'}]
pwa: {
workbox: {
cachingExtensions: "@/plugins/workbox-range-request.js",
skipWaiting: true
},
}
export default async (context) => {
const workbox = await window.$workbox;
if (!workbox) {
console.debug("Workbox couldn't be loaded.");
return;
}
workbox.addEventListener('installed', (event) => {
if (!event.isUpdate) {
console.debug('The PWA is on the latest version.');
return;
}
console.debug('There is an update for the PWA, reloading...');
window.location.reload(true);
});
};
workbox.routing.registerRoute(
/\.(mp4|webm)/,
workbox.strategies.cacheFirst({
plugins: [
new workbox.rangeRequests.Plugin(),
],
}),
'GET'
);
workbox.routing.setCatchHandler(({url, event, params}) => {
const strategy = new workbox.strategies.NetworkFirst({networkTimeoutSeconds: 10});
return strategy.handle({
request: new Request(url),
});
});
workbox.routing.registerRoute(
/\/_nuxt\/.*(?:js|css)$/,
new workbox.strategies.StaleWhileRevalidate({
cacheName: `css_js_new_today_${Date.now() + Math.random()}`,
}),
'GET',
);
workbox.routing.registerRoute(
({ url, request }) =>
url.origin === 'your content domain' &&
request.destination === 'image',
new workbox.strategies.StaleWhileRevalidate({
cacheName: `product_new_today_${Date.now() + Math.random()}`,
plugins: [
new workbox.expiration.ExpirationPlugin({
// Only cache 60 images.
maxEntries: 60,
purgeOnQuotaError: true,
}),
],
}),
);
workbox.routing.registerRoute(
/\.(?:png|gif|jpg|jpeg|svg|webp)$/,
new workbox.strategies.StaleWhileRevalidate({
cacheName: `images_new_today_${Date.now() + Math.random()}`,
plugins: [
new workbox.expiration.ExpirationPlugin({
// Only cache 60 images.
maxEntries: 60,
purgeOnQuotaError: true,
}),
],
}),
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment