Last active
March 31, 2018 19:52
-
-
Save devNigel/37b761ad662849ee38c271d7ba93bb89 to your computer and use it in GitHub Desktop.
Beginner’s Guide to Converting a Javascript App to a Progressive Web App (PWA)
This file contains hidden or 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 alertBox = document.getElementById("updateNotification"); | |
| const updateButton = document.getElementById("updateButton"); | |
| if ('serviceWorker' in navigator) { | |
| window.addEventListener('load', function () { | |
| navigator.serviceWorker.register('sw.js').then(function (registration) { | |
| //check if page was loaded via service worker | |
| if (!navigator.serviceWorker.controller) { | |
| return; | |
| } | |
| // if updated service worker is waiting | |
| if (registration.waiting) { | |
| console.log("sw waiting") | |
| updateReady(registration.waiting); | |
| } | |
| //if service worker is installing | |
| if (registration.installing) { | |
| //track installing | |
| console.log("sw installing") | |
| trackInstalling(registration.installing); | |
| return; | |
| } | |
| //listen for service worker update | |
| registration.addEventListener('updatefound', function () { | |
| console.log("updatefound") | |
| trackInstalling(registration.installing); | |
| }) | |
| // Registration was successful | |
| console.log('ServiceWorker registration successful with scope: ', registration.scope); | |
| }, function (err) { | |
| // registration failed :( | |
| console.log('ServiceWorker registration failed: ', err); | |
| }); | |
| }); | |
| } | |
| function trackInstalling(worker) { | |
| worker.addEventListener('statechange', function () { | |
| if (worker.state == 'installed') { | |
| updateReady(worker); | |
| } | |
| }) | |
| } | |
| function updateReady(worker) { | |
| alertBox.style.display = "block"; | |
| updateButton.addEventListener('click', function () { | |
| worker.postMessage({ action: 'skipWaiting' }); | |
| }); | |
| } | |
| navigator.serviceWorker.addEventListener("controllerchange", function () { | |
| window.location.reload(); | |
| }) | |
| /* | |
| game logic | |
| *? |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment