Skip to content

Instantly share code, notes, and snippets.

@tonyedwardspz
Last active April 5, 2016 13:41
Show Gist options
  • Save tonyedwardspz/cef4fe098dd2a47b5167586fbffcfd3a to your computer and use it in GitHub Desktop.
Save tonyedwardspz/cef4fe098dd2a47b5167586fbffcfd3a to your computer and use it in GitHub Desktop.
Simple Service Worker asset caching script - see http://purelywebdesign.co.uk/tutorial/service-worker-caching-tutorial/
'use strict';
var CACHE_NAME = 'psw-cache-v1';
var urlsToCache = [
'/assets/site-logo.svg',
'/css/main.css',
'/javascript/application.js'
];
self.addEventListener('install', function(event) {
// Open device cache and store our list of items
event.waitUntil(
caches.open(CACHE_NAME).then(function(cache) {
return cache.addAll(urlsToCache);
})
);
});
self.addEventListener('fetch', function(event) {
// Intercept fetch request
event.respondWith(
// match and serve cached asset if it exists
caches.match(event.request).then(function(response) {
return response || fetch(event.request);
})
);
});
self.addEventListener('activate', function(event) {
event.waitUntil(
// Open our apps cache and delete any old cache items
caches.open(CACHE_NAME).then(function(cacheNames){
cacheNames.keys().then(function(cache){
cache.forEach(function(element, index, array) {
if (urlsToCache.indexOf(element) === -1){
caches.delete(element);
}
});
});
})
);
});
$(document).ready(function(){
'use strict';
// Check that service workers are available
if ('serviceWorker' in navigator) {
console.log('ServiceWorker available in navigator');
navigator.serviceWorker.register('/serviceWorkerClient.js').then(function(reg) {
console.log('ServiceWorker registration successful with scope: ', reg.scope);
}).catch(function(err) {
console.log('ServiceWorker registration failed: ', err);
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment