Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to lazy-load images

Short answer

Add the loading="lazy" attribute to the image:

<p style="height: 300px;">Scroll down ↓</p>
<img src="/media/photo-400x250.jpg" alt="A flower" width="400" height="250" loading="lazy">

The browser starts loading the image only when it gets close to the visible area. The page opens faster, and a visitor who does not scroll to the end does not spend data on extra files.

Do not forget the sizes

Until the image loads, the browser does not know its height. The width and height attributes give the proportions in advance, and space is reserved right away — the text does not jump when the image appears.

Video in an iframe

The same attribute works on <iframe> — embedded maps and videos also start loading only when scrolled to:

<iframe src="https://example.com" title="Example site" width="300" height="150" loading="lazy"></iframe>

What to load right away

For images at the top of the page that are visible immediately, lazy loading hurts: the browser postpones them, and the main banner appears later. Such an image can instead get a higher priority with fetchpriority="high".

Common mistake

loading="lazy" is put on every image, including the logo and the cover on the first screen. The site starts to feel slower, not faster. Defer only what is below the first screen.

Functions used in this recipe

  • loading — Lazy loading for images and frames that are not yet visible.
  • <img> — An image.
  • <iframe> — Embeds another page inside the current one: a map, a video, a widget.

Thanks for reading!

Donate to the site — we work hard for you.