Skip to content

Instantly share code, notes, and snippets.

@73nko
Forked from ireade/sw.js
Created December 20, 2018 07:47
Show Gist options
  • Save 73nko/6e4655c67938258ffb61defc9d9d2cd4 to your computer and use it in GitHub Desktop.
Save 73nko/6e4655c67938258ffb61defc9d9d2cd4 to your computer and use it in GitHub Desktop.
Handle broken images with the service worker
self.addEventListener('install', (e) => {
e.waitUntil(
caches.open("precache").then((cache) => cache.add("/broken.png"))
);
});
function isImage(fetchRequest) {
return fetchRequest.method === "GET" && fetchRequest.destination === "image";
}
self.addEventListener('fetch', (e) => {
e.respondWith(
fetch(e.request)
.then((response) => {
if (response.ok) return response;
// User is online, but response was not ok
if (isImage(e.request)) {
// Get broken image placeholder from cache
return caches.match("/broken.png");
}
})
.catch((err) => {
// User is probably offline
if (isImage(e.request)) {
// Get broken image placeholder from cache
return caches.match("/broken.png");
}
}) // end fetch
)
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment