Skip to content

Instantly share code, notes, and snippets.

@alexpermiakov
Last active December 23, 2019 14:19
Show Gist options
  • Save alexpermiakov/39b69626fa688c2f30db87938a003886 to your computer and use it in GitHub Desktop.
Save alexpermiakov/39b69626fa688c2f30db87938a003886 to your computer and use it in GitHub Desktop.
const CACHE_NAME = "cache-<%= buildVersion %>";
const urlsToCache = ['/', '/css/main.css', '/js/main.js', <%= buildFiles %>];
self.addEventListener("install", async e => {
self.skipWaiting();
e.waitUntil(cacheResources());
});
const cacheResources = async () => {
const cache = await caches.open(CACHE_NAME);
return cache.addAll(urlsToCache);
};
self.addEventListener("activate", e => {
e.waitUntil(clearOldCache());
});
const clearOldCache = async () => {
const cacheNames = await caches.keys();
const oldCacheName = cacheNames.find(name => name !== CACHE_NAME);
caches.delete(oldCacheName);
};
self.addEventListener("fetch", e => {
e.respondWith(getResponseByRequest(e.request));
});
const getResponseByRequest = async request => {
const cache = await caches.open(CACHE_NAME);
const cachedResponse = await cache.match(request);
return cachedResponse || (await fetch(request));
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment