Last active
May 31, 2018 00:04
-
-
Save Hidden50/3c62a415745f931385a0036ce1ad70c8 to your computer and use it in GitHub Desktop.
basic Service Worker example
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
// ... | |
window.addEventListener('load', () => { | |
if('serviceWorker' in navigator) { | |
navigator.serviceWorker.register( './sw.min.js', { scope: "./" } ) | |
.then( registration => { | |
const newWorker = registration.installing; | |
if (newWorker) { | |
newWorker.onstatechange = function() { | |
if (newWorker.state == 'activated' && !navigator.serviceWorker.controller) { | |
// tell the user they can use the page without an internet connection | |
document.documentElement.classList.add('offline-ready'); | |
} | |
}; | |
} | |
}); | |
} | |
}); | |
// ... |
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 version = "3.0.0-{%INSERT-DATE%}"; // I use a gulp task to insert this value at build time | |
// to make sure the service worker changes with every release | |
const expectedCaches = [`v${version}`]; | |
const required = [ | |
`/`, | |
`./index.html`, | |
`./sprites.png`, | |
`./stylesheet.min.css`, | |
`./scripts.min.js`, | |
`https://code.jquery.com/jquery-3.2.1.slim.min.js`, | |
`https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js`, | |
`https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js`, | |
]; | |
self.addEventListener('install', e => { | |
// | |
// fires when the browser sees this version of the service worker for the first time | |
// | |
console.log(`Service Worker: Installing version ${version}`); | |
e.waitUntil( | |
caches.open(`v${version}`).then(cache => { | |
return cache.addAll(required) | |
.then(() => self.skipWaiting()); | |
}) | |
); | |
}); | |
self.addEventListener('activate', e => { | |
// | |
// fires when the service worker goes live | |
// (workers remain inactive until their previous version is stopped) | |
// | |
requestCount = 0; | |
console.log(`Service Worker: Activating version ${version}`); | |
e.waitUntil(self.clients.claim()); | |
e.waitUntil( | |
caches.keys().then( cacheNames => { | |
return Promise.all( cacheNames.map( thisCacheName => { | |
if (!expectedCaches.includes(thisCacheName)) { | |
console.log(`Service Worker: Deleting cache ${thisCacheName}`); | |
return caches.delete(thisCacheName); | |
} | |
})); | |
}) | |
); | |
}); | |
self.addEventListener('fetch', e => { | |
// | |
// fires for every page request within the service worker's scope | |
// also for requests made by those pages | |
// | |
if (e.request.url.endsWith('/') || e.request.url.endsWith('.html')) { | |
console.log(`Service Worker: Version ${version}, loading page`); | |
} | |
e.respondWith( | |
// cache lookup | |
caches.match(e.request).then( cachedResponse => { | |
// found in cache? | |
if (cachedResponse) { | |
console.log(`Service Worker: Serving ${e.request.url} from cache`); | |
return cachedResponse; | |
} | |
// fetch from the web | |
let requestClone = e.request.clone(); | |
return fetch(requestClone).then( response => { | |
// sanity check before caching | |
if (!response || !e.request.url.startsWith(location.origin)) { | |
if (!e.request.url.startsWith(location.origin)) | |
console.log(`Service Worker: Not caching ${e.request.url} (external url).`); | |
return response; | |
} | |
// cache | |
let responseClone = response.clone(); | |
return caches.open(`v${version}`).then( cache => { | |
console.log(`Service Worker: Caching ${e.request.url}`); | |
cache.put(e.request, responseClone); | |
return response; | |
}); | |
}); | |
}) | |
); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment