Skip to content

Instantly share code, notes, and snippets.

@gokulkrishh
Forked from adactio/basicServiceWorker.js
Created January 14, 2016 03:57
Show Gist options
  • Save gokulkrishh/aaabd9ce32589606b664 to your computer and use it in GitHub Desktop.
Save gokulkrishh/aaabd9ce32589606b664 to your computer and use it in GitHub Desktop.
A basic Service Worker, for use on, say, a blog.
'use strict';
(function() {
// Update 'version' if you need to refresh the cache
var staticCacheName = 'static';
var version = 'v1::';
// Store core files in a cache (including a page to display when offline)
function updateStaticCache() {
return caches.open(version + staticCacheName)
.then(function (cache) {
return cache.addAll([
'/path/to/javascript.js',
'/path/to/stylesheet.css',
'/path/to/someimage.png',
'/path/to/someotherimage.png',
'/',
'/offline.html'
]);
});
};
self.addEventListener('install', function (event) {
event.waitUntil(updateStaticCache());
});
self.addEventListener('activate', function (event) {
event.waitUntil(
caches.keys()
.then(function (keys) {
// Remove caches who's name in no longer valid
return Promise.all(keys
.filter(function (key) {
return key.indexOf(version) !== 0;
})
.map(function (key) {
return caches.delete(key);
})
);
})
);
});
self.addEventListener('fetch', function (event) {
var request = event.request;
// Always fetch non-GET requests from the network
if (request.method !== 'GET') {
event.respondWith(
fetch(request, { credentials: 'include' })
.catch(function () {
return caches.match('/offline.html');
})
);
return;
}
// For HTML requests, try the network first, fall back to the cache, finally the offline page
if (request.headers.get('Accept').indexOf('text/html') !== -1) {
event.respondWith(
fetch(request, { credentials: 'include' })
.then(function (response) {
caches.open(version + staticCacheName)
.then(function (cache) {
cache.put(request, response.clone());
});
return response;
})
.catch(function () {
return caches.match(request)
.then(function (response) {
return response || caches.match('/offline.html');
})
})
);
return;
}
// For non-HTML requests, look in the cache first, fall back to the network
event.respondWith(
caches.match(request)
.then(function (response) {
return response || fetch(request);
})
);
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment