Subscribe

Image Lazy Loading

✍️

Lazy loading was never this easy! 😴

6 Jun, 2020 · 2 min read

Lazy loading has been a term that was hot about 15 years ago and never stopped being in fashion. The images are mostly the heaviest part of a website and tend to slow everything down.

It was always pretty tedious to make a custom JavaScript for lazy loading, but we now have the native lazy loading API!

It can be as simple as adding loading="lazy" to an image element.

HTML Structure

<img
  src="https://images.unsplash.com/photo-1591303872989-2640dc28185b?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=3236&q=80"
  loading="lazy"
  onload="alert('Cool right!');"
/>

We can define the loading attribute and give it the value of lazy, and the API comes with an onload callback function.

Other values we can use are:

  • auto - Default behavior, browser-specific
  • lazy - Loads the image when it becomes visible based on scroll
  • eager - Loads the image directly

See this in action on the following Codepen.

See the Pen Image Lazy Loading by Chris Bongers (@rebelchris) on CodePen.

Browser Support

Unfortunately, it’s not fully supported by all browsers, but keep in mind if the browser doesn’t support it, it will just show the image, so there is no harm in adding this!

Lazy loading support

Thank you for reading, and let’s connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next 📖

Submit button outside the form

4 Dec, 2022 · 1 min read

Submit button outside the form

Trying out native dialog modals

8 Aug, 2022 · 3 min read

Trying out native dialog modals

Join 2099 devs and subscribe to my newsletter