Skip to content

Commit

Permalink
Use a resized image as fallback image. Fixes google#81
Browse files Browse the repository at this point in the history
  • Loading branch information
cramforce committed May 6, 2021
1 parent d7f6305 commit 832bafc
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 6 deletions.
10 changes: 7 additions & 3 deletions _11ty/img-dim.js
Original file line number Diff line number Diff line change
Expand Up @@ -98,26 +98,30 @@ const processImage = async (img, outputPath) => {
avif.setAttribute("type", "image/avif");
await setSrcset(webp, src, "webp");
webp.setAttribute("type", "image/webp");
await setSrcset(jpeg, src, "jpeg");
const fallback = await setSrcset(jpeg, src, "jpeg");
jpeg.setAttribute("type", "image/jpeg");
picture.appendChild(avif);
picture.appendChild(webp);
picture.appendChild(jpeg);
img.parentElement.replaceChild(picture, img);
picture.appendChild(img);
img.setAttribute("src", fallback);
} else if (!img.getAttribute("srcset")) {
await setSrcset(img, src, "jpeg");
const fallback = await setSrcset(img, src, "jpeg");
img.setAttribute("src", fallback);
}
};

async function setSrcset(img, src, format) {
img.setAttribute("srcset", await srcset(src, format));
const setInfo = await srcset(src, format);
img.setAttribute("srcset", setInfo.srcset);
img.setAttribute(
"sizes",
img.getAttribute("align")
? "(max-width: 608px) 50vw, 187px"
: "(max-width: 608px) 100vw, 608px"
);
return setInfo.fallback;
}

const dimImages = async (rawContent, outputPath) => {
Expand Down
5 changes: 4 additions & 1 deletion _11ty/srcset.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,10 @@ module.exports = async function srcset(filename, format) {
const names = await Promise.all(
widths.map((w) => resize(filename, w, format))
);
return names.map((n, i) => `${n} ${widths[i]}w`).join(", ");
return {
srcset: names.map((n, i) => `${n} ${widths[i]}w`).join(", "),
fallback: names[0],
};
};

async function resize(filename, width, format) {
Expand Down
5 changes: 3 additions & 2 deletions test/test-generic-post.js
Original file line number Diff line number Diff line change
Expand Up @@ -149,8 +149,9 @@ describe("check build output for a generic post", () => {
const picture = pictures[0];
const sources = Array.from(picture.querySelectorAll("source"));
expect(sources).to.have.length(3);
expect(img.src).to.match(/\/img\/remote\/\w+\.jpg/);
expect(metaImage).to.equal(URL + img.src);
expect(img.src).to.match(/^\/img\/remote\/\w+-1920w\.jpg$/);
expect(metaImage).to.match(new RegExp(URL));
expect(metaImage).to.match(/\/img\/remote\/\w+\.jpg$/);
const avif = sources.shift();
const webp = sources.shift();
const jpg = sources.shift();
Expand Down

0 comments on commit 832bafc

Please sign in to comment.