Skip to content

Instantly share code, notes, and snippets.

@ngohungphuc
Last active December 3, 2018 17:07
Show Gist options
  • Save ngohungphuc/63e040761bc9c0e65d037f5725f21724 to your computer and use it in GitHub Desktop.
Save ngohungphuc/63e040761bc9c0e65d037f5725f21724 to your computer and use it in GitHub Desktop.
var cacheName = "app-cache-v1";
var offlineUrl = "./offline.html";
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",
offlineUrl
])
).then(() => self.skipWaiting())
);
});
// 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;
}).catch(error => {
// Check if the user is offline first and is trying to navigate to a web page
if (event.request.method === 'GET' && event.request.headers.get('accept').includes('text/html')) {
// Return the offline page
return caches.match(offlineUrl);
}
});
})
);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment