Create a gist now

Instantly share code, notes, and snippets.

Embed
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/service-worker.js');
}
const CACHE_PREFIX = 'Client';
const CACHE_VERSION = 'v1';
const CACHE_NAME = `${ CACHE_PREFIX }-${ CACHE_VERSION }`;
const CACHE_URLS = [
'/dist/offline.html',
'/dist/vendors.js',
'/dist/common.js',
'/dist/common.css'
];
const OFFLINE_URL = '/dist/offline.html';
function openCache() {
return caches.open(CACHE_NAME);
}
function addToCache(request, response) {
return openCache()
.then((cache) => {
return cache.put(request, response.clone());
});
}
function precache() {
return openCache()
.then((cache) => {
return cache.addAll(CACHE_URLS);
})
.then(() => self.skipWaiting());
}
function fromInternet(request) {
return fetch(request)
.then((response) => {
if (response) {
return addToCache(request, response)
.then(() => response);
}
return response;
});
}
function fromCache(request) {
return openCache()
.then((cache) => {
return cache
.match(request)
.then((matching) => {
if (matching) {
return matching;
}
return fromInternet(request);
});
});
}
self.addEventListener('install', (event) => {
event.waitUntil(precache());
});
self.addEventListener('activate', (event) => {
event.waitUntil(
caches
.keys()
.then((cacheKeys) => {
const deletePromises = cacheKeys
.filter(key => key.indexOf(CACHE_NAME) !== 0)
.map(oldKey => caches.delete(oldKey));
return Promise.all(deletePromises);
})
.then(() => self.clients.claim())
);
});
self.addEventListener('fetch', (event) => {
const request = event.request;
const url = new URL(request.url);
const acceptHeader = request.headers.get('Accept');
if (
(request.method === 'GET') &&
(acceptHeader.indexOf('text/html') === -1) &&
(
(url.origin === self.location.origin) ||
(url.origin.indexOf('fonts.gstatic.com') !== -1) ||
(url.origin.indexOf('fonts.googleapis.com') !== -1)
)
) {
event.respondWith(fromCache(request));
} else if (
(event.request.method === 'GET') &&
(acceptHeader.indexOf('text/html') !== -1)
) {
event.respondWith(
fetch(request)
.catch(() => {
return caches.match(OFFLINE_URL);
})
);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment