diff --git a/.changeset/lazy-source-fetch.md b/.changeset/lazy-source-fetch.md new file mode 100644 index 0000000..bb69395 --- /dev/null +++ b/.changeset/lazy-source-fetch.md @@ -0,0 +1,5 @@ +--- +"@solidjs/image": patch +--- + +A lazy `SolidImage` no longer renders its `` tags until it is eager or near the viewport, so the browser no longer downloads an offscreen variant before the image scrolls into view. diff --git a/src/__tests__/browser/solid-image.test.tsx b/src/__tests__/browser/solid-image.test.tsx index 1a42e58..9767a74 100644 --- a/src/__tests__/browser/solid-image.test.tsx +++ b/src/__tests__/browser/solid-image.test.tsx @@ -171,6 +171,34 @@ describe("SolidImage in the browser", () => { expect(sources[0]!.srcset).toBe(`${PIXEL} 400w,${PIXEL} 800w`); }); + it("does not fetch the preferred variant before the image scrolls into view", async () => { + const stamp = Date.now(); + const preferred = new URL(`/lazy-variant-${stamp}.webp`, location.href).href; + const fallback = new URL(`/lazy-variant-${stamp}.png`, location.href).href; + const { host, scrollIntoView } = mount(() => ( + [ + { path: preferred, width: 400, type: "image/webp" }, + { path: fallback, width: 400, type: "image/png" }, + ], + }} + /> + )); + + await expect.poll(() => host.querySelector("noscript")).toBe(null); + await new Promise(resolve => setTimeout(resolve, 100)); + + expect(host.querySelector("source")).toBe(null); + expect(performance.getEntriesByName(preferred)).toHaveLength(0); + + scrollIntoView(); + + await expect.poll(() => performance.getEntriesByName(preferred)).toHaveLength(1); + }); + it("drops the inline placeholder once the image has loaded", async () => { const { host, scrollIntoView } = mount(() => ( { expect(outsideNoscript).not.toContain("hero.png"); }); + it("renders no for a lazy image on the server", () => { + const html = renderToString(() => ( + [ + { path: "/hero-400.webp", width: 400, type: "image/webp" }, + { path: "/hero-400.jpg", width: 400, type: "image/jpeg" }, + ], + }} + fallback={() =>
loading
} + /> + )); + + const outsideNoscript = html.replace(/]*>.*?<\/noscript>/gs, ""); + expect(outsideNoscript).not.toContain(" { const html = renderToString(() => ( { [ @@ -169,6 +190,7 @@ describe("SolidImage SSR", () => { [{ path: "/hero-400.webp", width: 400, type: "image/webp" }], }} @@ -239,6 +261,7 @@ describe("SolidImage SSR", () => { [ { path: "/hero-400.webp", width: 400, type: "image/webp" }, diff --git a/src/core/index.tsx b/src/core/index.tsx index 9f7cdf4..5c4ba80 100644 --- a/src/core/index.tsx +++ b/src/core/index.tsx @@ -277,7 +277,10 @@ export function SolidImage(props: SolidImageProps): JSX.Element {
- + {/* A picture's source is fetched on sight, whatever the img's src. */} + + +