Last active
December 23, 2019 14:19
-
-
Save alexpermiakov/39b69626fa688c2f30db87938a003886 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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