Skip to content

Commit

Permalink
refactor image loading code
Browse files Browse the repository at this point in the history
  • Loading branch information
SimonSiefke committed Mar 9, 2022
1 parent 82496a6 commit b1d5fdf
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 6 deletions.
20 changes: 15 additions & 5 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,18 @@ const registerServiceWorker = async () => {

const imgSection = document.querySelector("section");

const createGalleryFigure = (galleryImage) => {
const getImageBlob = async (url) => {
const imageResponse = await fetch(url);
if (!imageResponse.ok) {
throw new Error(
"Image didn't load successfully; error code:" + imageResponse.statusText
);
}
return imageResponse.blob();
};

const createGalleryFigure = async (galleryImage) => {
const imageBlob = await getImageBlob(galleryImage.url);
const myImage = document.createElement("img");
const myCaption = document.createElement("caption");
const myFigure = document.createElement("figure");
Expand All @@ -27,11 +38,10 @@ const createGalleryFigure = (galleryImage) => {
galleryImage.name +
"</strong>: Taken by " +
galleryImage.credit;
myImage.src = galleryImage.url;
myImage.src = window.URL.createObjectURL(imageBlob);
myImage.setAttribute("alt", galleryImage.alt);
myImage.onerror = () => console.log(`image failed to load: ${myImage.src}`);
myFigure.append(myImage, myCaption);
return myFigure;
imgSection.append(myFigure);
};

window.onload = async () => {
Expand All @@ -43,5 +53,5 @@ window.onload = async () => {
return;
}
}
imgSection.append(...Gallery.images.map(createGalleryFigure));
await Promise.allSettled(Gallery.images.map(createGalleryFigure));
};
2 changes: 1 addition & 1 deletion sw.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ const cacheFirst = async ({ request, fallbackUrl }) => {
}
// when the even fallback response is not available,
// there is nothing we can do, but we must always
// return a response
// return a Response object
return new Response("Network error happened", {
status: 408,
headers: { "Content-Type": "text/plain" },
Expand Down

0 comments on commit b1d5fdf

Please sign in to comment.