registerServiceWorker.js 2.1 KB

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