Last active
May 28, 2024 19:17
-
-
Save ireade/128adedc16bf1bd1de98397d437c339d to your computer and use it in GitHub Desktop.
Handle broken images with the service worker
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
when first timen brower website, image error occur may happen before the 'broken.jpg' cached. sw scheme can coopera with css scheme。