Skip to content

Instantly share code, notes, and snippets.

@andreasonny83
Last active January 18, 2017 14:27
Show Gist options
  • Save andreasonny83/3d2684562f455564737afd3d675d873f to your computer and use it in GitHub Desktop.
Save andreasonny83/3d2684562f455564737afd3d675d873f to your computer and use it in GitHub Desktop.
Service Worker
// https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers
// app.js
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw-test/sw.js', { scope: '/sw-test/' }).then(function(reg) {
if(reg.installing) {
console.log('Service worker installing');
} else if(reg.waiting) {
console.log('Service worker installed');
} else if(reg.active) {
console.log('Service worker active');
}
}).catch(function(error) {
// registration failed
console.log('Registration failed with ' + error);
});
}
// sw.js
this.addEventListener('install', function(event) {
event.waitUntil(
caches.open('v1').then(function(cache) {
return cache.addAll([
'/sw-test/',
'/sw-test/index.html',
'/sw-test/*.css',
'*.js',
'/sw-test/assets/*.jpg'
]);
})
);
});
this.addEventListener('fetch', function(event) {
var response;
event.respondWith(caches.match(event.request).catch(function() {
return fetch(event.request);
}).then(function(r) {
response = r;
caches.open('v1').then(function(cache) {
cache.put(event.request, response);
});
return response.clone();
}).catch(function() {
return caches.match('/sw-test/gallery/myLittleVader.jpg');
}));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment