Skip to content

Support for background-image optimization #55

@georges-gomes

Description

@georges-gomes

I got these insights from someone in the Astro lounge on Discord


---
/** snip */
const originalWidth = 1740;
const { image: bgHeroImage, sources: bgHeroSources } = await getPicture({
  src: import("@screens/index/bg-hero.jpg") as unknown as Promise<{ default: ImageMetadata }>,
  formats: ["avif", "jpeg", "webp"],
  widths: [originalWidth / 2, originalWidth],
});

const bgHeroImageSrc = (bgHeroImage as { src: string }).src;

const bgHeroSourcesRemapped = bgHeroSources.flatMap(({ type, srcset }) => {
  const sources = srcset.split(",");

  return sources.map((unparsedSource) => {
    const [source, width] = unparsedSource.split(" ");
    return { type, source, width };
  });
});

const imageSet = `
background-image: url("${bgHeroImageSrc}");
background-image: -webkit-image-set(
  ${bgHeroSourcesRemapped
    .filter(({ type }) => type !== "image/avif")
    .map(({ source, width }) => {
      const resolution = width === `${originalWidth}w` ? "2x" : "1x";
      return `url('${source}') ${resolution}`;
    })
    .join(",\n")}
);
background-image: image-set(
  ${bgHeroSourcesRemapped
    .map(({ type, source, width }) => {
      const resolution = width === `${originalWidth}w` ? "2x" : "1x";
      return `url('${source}') ${resolution} type("${type}")`;
    })
    .join(",\n")}
);
`;
---
<!-- example: -->
<div style={imageSet}/>

for image-set support on my astro site - image-set support is fun to figure out though 😅 since there's not amazing support for all of the values, for example, safari will try to use an avif if i include it in -webkit-image-set b/c safari and chrome don't support the type() clause and safari doesnt' support avif

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions