diff --git a/generate-html.js b/generate-html.js
index 24af12c..9a5a1a1 100644
--- a/generate-html.js
+++ b/generate-html.js
@@ -10,10 +10,11 @@ const LOWSRC_FORMAT_PREFERENCE = ["jpeg", "png", "gif", "svg", "webp", "avif"];
/*
Returns:
e.g. { img: { alt: "", src: "" }
+ e.g. { img: { alt: "", src: "", srcset: "", sizes: "" } }
e.g. { picture: [
{ source: { srcset: "", sizes: "" } },
{ source: { srcset: "", sizes: "" } },
- { img: { alt: "", src: "" } },
+ { img: { alt: "", src: "", srcset: "", sizes: "" } },
]}
*/
function generateObject(metadata, attributes = {}) {
@@ -96,7 +97,7 @@ function generateObject(metadata, attributes = {}) {
let children = [];
values.filter(imageFormat => {
- return imageFormat.length > 0 && (lowsrcFormat !== imageFormat[0].format || imageFormat.length !== 1);
+ return imageFormat.length > 0 && (lowsrcFormat !== imageFormat[0].format);
}).forEach(imageFormat => {
if(imageFormat.length > 1 && !attributes.sizes) {
// Per the HTML specification sizes is required srcset is using the `w` unit
@@ -119,8 +120,31 @@ function generateObject(metadata, attributes = {}) {
});
});
+ /*
+ Add lowsrc as an img, for browsers that don’t support picture or the formats provided in source
+
+ If we have more than one size, we can use srcset and sizes.
+ If the browser doesn't support those attributes, it should ignore them.
+ */
+ let imgAttributes = Object.assign({}, attributesWithoutSizes);
+ if (Object.values(lowsrc).length > 1) {
+ if (!attributes.sizes) {
+ // Per the HTML specification sizes is required srcset is using the `w` unit
+ // https://html.spec.whatwg.org/dev/semantics.html#the-link-element:attr-link-imagesrcset-4
+ // Using the default "100vw" is okay
+ throw new Error(missingSizesErrorMessage);
+ }
+
+ let srcsetAttrValue = Object.values(lowsrc).map(entry => entry.srcset).join(", ");
+ if (srcsetAttrValue) {
+ imgAttributes.srcset = srcsetAttrValue;
+
+ imgAttributes.sizes = attributes.sizes;
+ }
+ }
+
children.push({
- "img": attributesWithoutSizes
+ "img": imgAttributes
});
return {
diff --git a/test/test-markup.js b/test/test-markup.js
index 6987437..e50c376 100644
--- a/test/test-markup.js
+++ b/test/test-markup.js
@@ -72,8 +72,7 @@ test("Image markup (two widths)", async t => {
sizes: "100vw",
}), [``].join(""));
});