Skip to content

Instantly share code, notes, and snippets.

@ireade ireade/sw.js
Last active Mar 20, 2019

Embed
What would you like to do?
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
)
});
@athlonUA

This comment has been minimized.

Copy link

athlonUA commented Dec 21, 2018

👍 Yep, works fine. Full example here https://github.com/athlonUA/sw-fail-images

@fanjunzhi

This comment has been minimized.

Copy link

fanjunzhi commented Jan 7, 2019

when first timen brower website, image error occur may happen before the 'broken.jpg' cached. sw scheme can coopera with css scheme。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.