Last active
June 20, 2018 15:51
-
-
Save dlueth/27769a0cba115e75d4335001c9540334 to your computer and use it in GitHub Desktop.
JavaScript: Immediately active Service Worker #JavaScript
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
self.addEventListener('install', function(event) { | |
return self.skipWaiting(); | |
}); | |
self.addEventListener('activate', function(event) { | |
return event.waitUntil(self.clients.claim()); | |
}); |
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
function init() { | |
// do something after Service Worker is active | |
} | |
if('serviceWorker' in navigator && 'Promise' in global) { | |
app.worker = new Promise(function(resolve, reject) { | |
navigator.serviceWorker.register('path/to/serviceworker.js') | |
.then(function(registration) { | |
var serviceWorker; | |
if(serviceWorker = registration.installing || registration.waiting) { | |
serviceWorker.addEventListener('statechange', function(event) { | |
if(event.target.state === 'activated') { | |
resolve(); | |
} | |
}); | |
} | |
if(registration.active) { | |
resolve(); | |
} | |
}) | |
.catch(function() { | |
reject(); | |
}); | |
}) | |
.finally(init); | |
} else { | |
init(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment