In this lesson, you watched Rosa’s home page jump as the photo of plot 7 loaded, and kept the photo’s room with width and height. You also let the browser wait to fetch photos far down a page with lazy loading.
Key Points
- The browser lays out a page as soon as it has the HTML. An image is a separate file that arrives later, so an
<img>without a size starts as a box 0 pixels wide and 0 high. - The image’s size is written near the start of its file. As soon as those first bytes arrive, the browser learns the size and moves everything below the image, while the rest of the file is still downloading. On the home page, the Next Work Day heading jumped 586 pixels down, below the window.
- To see this on your own machine, open DevTools’ Network panel, which lists every file the page asks for. Tick its Disable cache box, or the browser reuses the image it already has and nothing jumps. Then pick 3G from its throttling menu and reload.
- Give every
<img>awidthand aheight, set to the image’s real size in pixels as plain numbers with no unit. The browser then keeps an empty box of that size from the start, and nothing moves when the image arrives. To find the size, open the image file in Chrome. The tab’s title shows it, for exampleplot-7.jpg (1200×896)for the course’s photo of Mei’s plot. The video’s copy of the photo was 800 by 600, so use the numbers of the file you have. - With no CSS yet,
widthandheightalso set the size the image shows at. Later, CSS will scale images to fit the screen, and the two numbers then give only the image’s shape, so the browser still keeps the right room for it. loading="lazy"lets the browser wait to fetch an image until the visitor scrolls near it. On a page of twelve photos, Chrome asked for all twelve at once without it. With it, Chrome asked for the six within about 3000 pixels below the window at first, then for each of the rest as scrolling brought it that close. Chrome picks that distance, and other browsers pick their own.- Leave lazy loading off images near the top of a page, like Mei’s photo on the home page. Visitors need those straight away. The browser asks for an ordinary image as soon as it reads its tag, but a lazy one waits until the page is laid out, so it can start later.
Final Code
The photo on Rosa’s home page, in index.html, now has its size: