Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for background-image optimization #55

Open
georges-gomes opened this issue Mar 18, 2023 · 0 comments
Open

Support for background-image optimization #55

georges-gomes opened this issue Mar 18, 2023 · 0 comments
Labels
enhancement New feature or request

Comments

@georges-gomes
Copy link
Member

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

@georges-gomes georges-gomes added the enhancement New feature or request label May 14, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

1 participant