Skip to content

Instantly share code, notes, and snippets.

@lejonmanen
Last active December 20, 2021 15:46
Show Gist options
  • Save lejonmanen/4744d6ae0a075ef501b270539ba55552 to your computer and use it in GitHub Desktop.
Save lejonmanen/4744d6ae0a075ef501b270539ba55552 to your computer and use it in GitHub Desktop.
Minimal service worker for use when developing a PWA
// Copy and paste this code into your main script file
// The purpose is to register the service worker
// The browser will load sw.js for us if you do this
if ('serviceWorker' in navigator) {
// Assumes your service worker has file name "sw.js"
navigator.serviceWorker.register('sw.js')
.then(reg => {
console.log('Registration succeeded. Scope is ' + reg.scope);
});
}
// The purpose of this file is to provide a minimal service worker file
// It is not complete, but it should be enough for you to get started
self.addEventListener('install', function(event) {
console.log('Service worker: install');
// Attempt to load cached files
});
self.addEventListener('fetch', function(event) {
console.log('Service worker: fetch');
// Look for cached files and handle AJAX failures due to being offline
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment