Skip to content

Instantly share code, notes, and snippets.

@federicofazzeri
Last active November 2, 2017 14:41
Show Gist options
  • Save federicofazzeri/8bb710ccaadc8ee6cb1d590797fc548f to your computer and use it in GitHub Desktop.
Save federicofazzeri/8bb710ccaadc8ee6cb1d590797fc548f to your computer and use it in GitHub Desktop.
Workbox setup to alert your users that a new version of your PWA is available on their device
function checkForNewVersions() {
if( ! 'BroadcastChannel' in window) return;
const assetsUpdates = new BroadcastChannel('precache-updates');
const dataUpdates = new BroadcastChannel('data-updates');
assetsUpdates.addEventListener('message', (event) => {
/*alert the user to reload the page to get the new app version*/
});
dataUpdates.addEventListener('message', (event) => {
/*alert the user to reload the page to get the new app data*/
});
}
if ('serviceWorker' in navigator) {
navigator.serviceWorker
.register('./sw.js')
.then((reg) => {
console.log('Service Worker Registered');
});
}
/* Create the service worker as the last step of your build */
const workboxBuild = require('workbox-build');
workboxBuild.generateSW({
globDirectory: './public/',
globPatterns: ['**\/*.{html,js,css}'], /*to be served from the cache*/
swDest: './public/sw.js',
runtimeCaching: [{
urlPattern: '/api', /*serve data from the cache but also update it with the new payload fetched from the network*/
handler: 'staleWhileRevalidate',
options: {
cacheName: 'data-cache',
cacheExpiration: {
maxEntries: 2
},
broadcastCacheUpdate: {
channelName: 'data-updates'
}
}
}],
skipWaiting: true
})
.then(() => {
console.log('Service worker generated.');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment