Skip to content

Instantly share code, notes, and snippets.

@ngohungphuc
Created November 29, 2018 16:21
Show Gist options
  • Save ngohungphuc/077a7c7adb12902e9227f697bf4bec0d to your computer and use it in GitHub Desktop.
Save ngohungphuc/077a7c7adb12902e9227f697bf4bec0d to your computer and use it in GitHub Desktop.
var cacheName = "app-cache-v1";
self.addEventListener("install", event => {
event.waitUntil(
caches
.open(cacheName)
.then(cache =>
cache.addAll([
"./dist/vendor.css",
"./css/site.min.css",
"./scripts/lib.js",
"./images/logo.png"
])
).then(() => self.skipWaiting())
);
});
//Removing outdated caches
self.addEventListener("activate", function (event) {
event.waitUntil(
caches.keys().then(function (cacheNames) {
return Promise.all(
cacheNames
.filter(function (cacheName) {
return true;
})
.map(function (cacheName) {
return caches.delete(cacheName);
})
);
}).then(() => self.clients.claim())
);
});
// Cache any new resources as they are fetched
self.addEventListener("fetch", function (event) {
//ignore these request
if (event.request.method !== "GET"
|| /api/.test(event.request.url)
|| event.request.destination === "document") {
return;
}
event.respondWith(
caches
.match(event.request, {
ignoreSearch: true
})
.then(function (response) {
if (response) {
return response;
}
var fetchRequest = event.request.clone();
return fetch(fetchRequest)
.then(function (res) {
if (!res || res.status !== 200) {
return res;
}
var responseToCache = res.clone();
caches.open(cacheName).then(function (cache) {
cache.put(event.request, responseToCache);
});
return res;
});
})
);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment