Tip: Lazy load images in HTML

Webdev, HTML, Image · Jun 12, 2021

Images are nowadays a crucial part of any webpage, but, as with most things, they come at a cost. Images are usually a major percentage of a page's load, which is why they make for a great candidate for optimization. The most common technique is that of lazy loading, usually in the form of delaying loading images outside the initial viewport until they are close to being scrolled into view.

This exact behavior is already part of the HTML standard in the form of the loading attribute. All you have to do to reap its benefits is add loading="lazy" to any images you want to add lazy loading to:

<img src="/img/duck.png" alt="A rubber duck" loading="lazy" />

Caveat: At the time of writing, the loading attribute is supported in most modern browsers, except for Safari, but not in legacy browsers, such as IE. On that note, lazy loading can be seen as a progressive enhancement for browsers that support it, so it's still worth adding for any users that can benefit from it.

Written by Angelos Chalaris

I'm Angelos Chalaris, a JavaScript software engineer, based in Athens, Greece. The best snippets from my coding adventures are published here to help others learn to code.

If you want to keep in touch, follow me on GitHub or Twitter.

More like this

  • Tips & Tricks

    A collection of quick tips and tricks to level up your coding skills one step at a time.

    Collection · 53 snippets

  • Tip: Customize the names of downloadable files

    Learn what HTML5 attribute you can use to customize the names of your downloadable files with this quick tip.

    HTML, Webdev · Jun 12, 2021

  • Tip: Prefetching resources in the browser

    Resource prefetching is a great technique to improve perceived page speed on your website and one that requires little to no effort. Learn how to use it today.

    HTML, Webdev · Jun 12, 2021

  • Tip: Create a descending list of numbered items

    Did you know there's an easy way to create a descending list of numbered items with pure HTML? Learn how with this handy tip.

    HTML, Webdev · Jun 22, 2021