|
| 1 | +// In production, we register a service worker to serve assets from local cache. |
| 2 | + |
| 3 | +// This lets the app load faster on subsequent visits in production, and gives |
| 4 | +// it offline capabilities. However, it also means that developers (and users) |
| 5 | +// will only see deployed updates on the "N+1" visit to a page, since previously |
| 6 | +// cached resources are updated in the background. |
| 7 | + |
| 8 | +// To learn more about the benefits of this model, read https://goo.gl/KwvDNy. |
| 9 | +// This link also includes instructions on opting out of this behavior. |
| 10 | + |
| 11 | +export default function register() { |
| 12 | + if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) { |
| 13 | + window.addEventListener('load', () => { |
| 14 | + const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`; |
| 15 | + navigator.serviceWorker |
| 16 | + .register(swUrl) |
| 17 | + .then(registration => { |
| 18 | + registration.onupdatefound = () => { |
| 19 | + const installingWorker = registration.installing; |
| 20 | + installingWorker.onstatechange = () => { |
| 21 | + if (installingWorker.state === 'installed') { |
| 22 | + if (navigator.serviceWorker.controller) { |
| 23 | + // At this point, the old content will have been purged and |
| 24 | + // the fresh content will have been added to the cache. |
| 25 | + // It's the perfect time to display a "New content is |
| 26 | + // available; please refresh." message in your web app. |
| 27 | + console.log('New content is available; please refresh.'); |
| 28 | + } else { |
| 29 | + // At this point, everything has been precached. |
| 30 | + // It's the perfect time to display a |
| 31 | + // "Content is cached for offline use." message. |
| 32 | + console.log('Content is cached for offline use.'); |
| 33 | + } |
| 34 | + } |
| 35 | + }; |
| 36 | + }; |
| 37 | + }) |
| 38 | + .catch(error => { |
| 39 | + console.error('Error during service worker registration:', error); |
| 40 | + }); |
| 41 | + }); |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +export function unregister() { |
| 46 | + if ('serviceWorker' in navigator) { |
| 47 | + navigator.serviceWorker.ready.then(registration => { |
| 48 | + registration.unregister(); |
| 49 | + }); |
| 50 | + } |
| 51 | +} |
0 commit comments