service-worker-registration.js 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /**
  2. * Copyright 2015 Google Inc. All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. /* eslint-env browser */
  17. 'use strict';
  18. if ('serviceWorker' in navigator) {
  19. // Delay registration until after the page has loaded, to ensure that our
  20. // precaching requests don't degrade the first visit experience.
  21. // See https://developers.google.com/web/fundamentals/instant-and-offline/service-worker/registration
  22. window.addEventListener('load', function() {
  23. // Your service-worker.js *must* be located at the top-level directory relative to your site.
  24. // It won't be able to control pages unless it's located at the same level or higher than them.
  25. // *Don't* register service worker file in, e.g., a scripts/ sub-directory!
  26. // See https://github.com/slightlyoff/ServiceWorker/issues/468
  27. navigator.serviceWorker.register('service-worker.js').then(function(reg) {
  28. // updatefound is fired if service-worker.js changes.
  29. reg.onupdatefound = function() {
  30. // The updatefound event implies that reg.installing is set; see
  31. // https://w3c.github.io/ServiceWorker/#service-worker-registration-updatefound-event
  32. var installingWorker = reg.installing;
  33. installingWorker.onstatechange = function() {
  34. switch (installingWorker.state) {
  35. case 'installed':
  36. if (navigator.serviceWorker.controller) {
  37. // At this point, the old content will have been purged and the fresh content will
  38. // have been added to the cache.
  39. // It's the perfect time to display a "New content is available; please refresh."
  40. // message in the page's interface.
  41. console.log('New or updated content is available.');
  42. } else {
  43. // At this point, everything has been precached.
  44. // It's the perfect time to display a "Content is cached for offline use." message.
  45. console.log('Content is now available offline!');
  46. }
  47. break;
  48. case 'redundant':
  49. console.error('The installing service worker became redundant.');
  50. break;
  51. }
  52. };
  53. };
  54. }).catch(function(e) {
  55. console.error('Error during service worker registration:', e);
  56. });
  57. });
  58. }