Created
January 29, 2017 21:19
-
-
Save anmolagrwl/640cf32cf53ef1f1d0e4b07d4ab2b5c8 to your computer and use it in GitHub Desktop.
react-pwa-simple
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function requestUpdate(sw) { | |
const shouldUpdate = window.confirm('New version available. Update?'); | |
if (shouldUpdate) { | |
sw.postMessage({ shouldUpdate: true }); | |
} | |
} | |
function checkStateForInstalled(sw) { | |
sw.addEventListener('statechange', () => { | |
if (sw.state === 'installed') { | |
requestUpdate(sw); | |
} | |
}); | |
} | |
navigator.serviceWorker.register('./sw.js').then((reg) => { | |
if (!navigator.serviceWorker.controller) { | |
return; | |
} | |
if (reg.waiting) { | |
requestUpdate(reg.waiting); | |
return; | |
} | |
if (reg.installing) { | |
checkStateForInstalled(reg.installing); | |
return; | |
} | |
reg.addEventListener('updatefound', () => { | |
checkStateForInstalled(reg.installing); | |
}); | |
}); | |
navigator.serviceWorker.addEventListener('controllerchange', () => window.location.reload()); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const VERSION = '{{VERSION}}'; | |
const appCache = `REACT-PWA-SIMPLE-${VERSION}`; | |
function deleteOldCaches(cacheNames) { | |
return Promise.all( | |
cacheNames | |
.filter(cacheName => cacheName.startsWith('REACT-PWA-SIMPLE')) | |
.filter(cacheName => (cacheName !== appCache)) | |
.map(cacheName => caches.delete(cacheName)) | |
); | |
} | |
self.addEventListener('install', (e) => { | |
const appUrls = [ | |
'./', | |
'./js/index.js', | |
'https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.5/css/bootstrap.min.css', | |
]; | |
const dataUrls = [ | |
'./data.json', | |
]; | |
caches.open(appCache).then(cache => cache.addAll(dataUrls)); | |
e.waitUntil( | |
caches.open(appCache).then(cache => cache.addAll(appUrls)) | |
); | |
}); | |
self.addEventListener('activate', (e) => { | |
self.clients.claim(); | |
e.waitUntil( | |
caches.keys().then(deleteOldCaches) | |
); | |
}); | |
self.addEventListener('fetch', (e) => { | |
e.respondWith( | |
caches.match(e.request).then(response => { | |
if (response) { | |
return response; | |
} | |
rturn fetch(e.request); | |
}) | |
); | |
}); | |
self.addEventListener('message', (e) => { | |
if (e.data.shouldUpdate) { | |
self.skipWaiting(); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment