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