The tea shop's brewing guide has photos, a video, and an embedded player, with their addresses in data-src. Until a photo arrives, the browser doesn't know how tall it will be, so it gives it no height, and when it loads, the text below it jumps down: a layout shift. Write reserveSpace(elements), which gives each element its size before it starts loading, from data-width and data-height, the file's width and height in pixels.
For an <img> or a <video>, set the width and height attributes to those numbers. The HTML Standard has browsers turn that pair into an aspect ratio, aspect-ratio: auto 1200 / 800, so with the shop's stylesheet (width: 100%; height: auto) the browser reserves the right height at any width, before a byte of the file arrives. The width and height attributes of an <iframe> don't give an aspect ratio, so for any other element set style.aspectRatio instead, such as "560 / 315", and no attributes.
Then start loading: set srcset from data-srcset when there is one, and set src from data-src last, so the size is always there first, as it would be in the HTML. A size counts only when data-width and data-height are both whole numbers above 0, written in digits only; otherwise set no size, since there's nothing right to reserve, and load the element anyway. Leave elements without a data-src alone.
// <img alt="Green tea" data-src="/teas/green.jpg" data-width="1200" data-height="800">
reserveSpace(document.querySelectorAll("img, video, iframe"));
// <img alt="Green tea" data-src="/teas/green.jpg" data-width="1200" data-height="800" width="1200" height="800" src="/teas/green.jpg">
const [green, mint] = document.querySelectorAll("img");
const video = document.querySelector("video");
reserveSpace(document.querySelectorAll("img, video, iframe"));
expect([green.getAttribute("width"), green.getAttribute("height")]).toEqual(["1200", "800"]);
expect([mint.getAttribute("width"), mint.getAttribute("height")]).toEqual(["1200", "900"]);
expect([video.getAttribute("width"), video.getAttribute("height")]).toEqual(["1920", "1080"]);
const observer = new MutationObserver(() => {});
observer.observe(document.body, { subtree: true, attributes: true, attributeFilter: ["width", "height", "style", "src", "srcset"] });
reserveSpace(document.querySelectorAll("img, video, iframe"));
const changes = new Map();
for (const record of observer.takeRecords()) {
const name = record.target.getAttribute("alt") || record.target.getAttribute("title") || record.target.tagName.toLowerCase();
changes.set(name, [...(changes.get(name) || []), record.attributeName]);
}
observer.disconnect();
expect([...changes.get("Green tea")].sort()).toEqual(["height", "src", "width"]);
expect(changes.get("Green tea").at(-1)).toBe("src");
expect(changes.get("Mint tea").slice(-2)).toEqual(["srcset", "src"]);
expect([...changes.get("Mint tea")].sort()).toEqual(["height", "src", "srcset", "width"]);
expect(changes.get("video").at(-1)).toBe("src");
expect(changes.get("How to brew oolong")).toEqual(["style", "src"]);
const [green, mint, logo] = document.querySelectorAll("img");
reserveSpace(document.querySelectorAll("img, video, iframe"));
expect(green.getAttribute("src")).toBe("/teas/green.jpg");
expect(mint.getAttribute("src")).toBe("/teas/mint-1200.jpg");
expect(mint.getAttribute("srcset")).toBe("/teas/mint-600.jpg 600w, /teas/mint-1200.jpg 1200w");
expect(green.hasAttribute("srcset")).toBe(false);
expect(document.querySelector("video").getAttribute("src")).toBe("/videos/pouring.mp4");
expect(document.querySelector("iframe").getAttribute("src")).toBe("/embed/brewing-oolong");
expect(logo.getAttribute("src")).toBe("/logo.svg");
const player = document.querySelector("iframe");
reserveSpace([player]);
expect(player.style.aspectRatio).toBe("560 / 315");
expect(player.hasAttribute("width")).toBe(false);
expect(player.hasAttribute("height")).toBe(false);
const [green, mint, logo] = document.querySelectorAll("img");
const video = document.querySelector("video");
green.dataset.width = "0";
mint.dataset.height = "900px";
video.dataset.width = "12.5";
reserveSpace([green, mint, logo, video]);
for (const element of [green, mint, logo, video]) {
expect(element.hasAttribute("width")).toBe(false);
expect(element.hasAttribute("height")).toBe(false);
expect(element.style.aspectRatio).toBe("");
}
expect([green, mint, logo, video].map((element) => element.getAttribute("src"))).toEqual(["/teas/green.jpg", "/teas/mint-1200.jpg", "/logo.svg", "/videos/pouring.mp4"]);
const leaf = document.querySelector('img[alt="Leaf"]');
const observer = new MutationObserver(() => {});
observer.observe(leaf, { attributes: true });
reserveSpace(document.querySelectorAll("img, video, iframe"));
expect(observer.takeRecords()).toHaveLength(0);
observer.disconnect();
expect([leaf.getAttribute("src"), leaf.getAttribute("width"), leaf.getAttribute("height")]).toEqual(["/leaf.svg", "24", "24"]);
Run tests runs every test on your code, here in your browser. The problem is solved when they all pass.
Ctrl + Enter runs the tests (⌘ + Enter on a Mac).
I'm here to help with Reserve space for images. I give hints, never the solution, so you get to solve it yourself. Ask for a hint, select code to ask about it, or press Ask Tuto why on a failing test.
Your first 3 answers need no account. for free to keep asking.