Skip to content

Instantly share code, notes, and snippets.

@devNigel
Last active March 31, 2018 19:52
Show Gist options
  • Select an option

  • Save devNigel/37b761ad662849ee38c271d7ba93bb89 to your computer and use it in GitHub Desktop.

Select an option

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)
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