Skip to content

Instantly share code, notes, and snippets.

@geowarin
Created June 28, 2017 14:57
Show Gist options
  • Save geowarin/d1a17f8ccc145e508c5b7c7702768273 to your computer and use it in GitHub Desktop.
Save geowarin/d1a17f8ccc145e508c5b7c7702768273 to your computer and use it in GitHub Desktop.
Uber service worker
function fetchNCache(e) {
return fetch(e).then(function(t) {
if (200 !== t.status)
return Promise.resolve(t);
const n = t.clone();
return caches.open(cacheName).then(function(s) {
return requestExpectsHtml(e) && !responseIsHtml(n) ? Promise.resolve(t) : void s.put(e.url, n)
}),
Promise.resolve(t)
})
}
function isCacheable(e) {
return cacheableAssetsPatterns.some(function(t) {
return t.test(e)
})
}
function requestExpectsHtml(e) {
if (!e || !e.headers)
return !1;
const t = e.headers.get("Accept");
return t && t.indexOf("html") > -1
}
function responseIsHtml(e) {
if (!e || !e.headers)
return !1;
const t = e.headers.get("content-type");
return t && t.indexOf("html") > -1
}
var cacheName = "1498515895721"
, coreBundleNames = ["https://d3i4yxtzktqr9n.cloudfront.net/lite/javascripts/app-41c1b254320dc7f685f1.js", "https://d3i4yxtzktqr9n.cloudfront.net/lite/javascripts/main-9b6c1b49974ce2e08a47.js", "https://d3i4yxtzktqr9n.cloudfront.net/lite/javascripts/vendor-5f9deee99fb86c0f8f20.js"]
, cacheableAssetsPatterns = [/^\/$/, /^(\/lite|\/lite-staging\/staging)?\/javascripts\//]
, HTML_TTL = 2592e5;
self.addEventListener("install", function(e) {
self.skipWaiting(),
e.waitUntil(caches.open(cacheName).then(function(e) {
return e.addAll(coreBundleNames)
}))
}),
self.addEventListener("activate", function(e) {
e.waitUntil(caches.keys().then(function(e) {
return Promise.all(e.map(function(e) {
if (e !== cacheName)
return caches["delete"](e)
}))
}))
}),
self.addEventListener("fetch", function(e) {
isCacheable(new URL(e.request.url).pathname) && e.waitUntil(e.respondWith(caches.match(e.request).then(function(t) {
if (t) {
if (requestExpectsHtml(e.request)) {
const n = new Date(t.headers.get("date")).valueOf();
Date.now() - n > HTML_TTL && fetchNCache(e.request)
}
return t
}
return fetchNCache(e.request)
})))
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment