DEV Community

Vesa Piittinen
Vesa Piittinen

Posted on

The perfect image lazy loading

Alright, lets get our JavaScript coding fingers ready for we are going to make the most awesomest image lazy loading!

<img
  alt="A giraffe eating fallback code solutions"
  src="giraffe.jpg"
  height="500"
  width="1000"
  loading="lazy"
/>
Enter fullscreen mode Exit fullscreen mode

Wait, what?

Yes, HTML is enough to perfectly solve this issue. Safari 15.4 now ships with lazy loading support. It was the last browser we waited for to catch up.

You no longer never need to do any JavaScript or CSS trickery related to typical image content loading.

But what about my fade in animation!

Don't do it. You should use a progressive image. The thing with progressive image is that once browser receives any image data it is able to start rendering at least something visual.

If you do image animation such as a fade in transition you are making a mistake. Without adding in lots of complex code you can only trigger a fade in transition once the entire image file is done loading. On slow connection this means the image will display, well, probably way after user has scrolled past the image.

This is an unnecessary cost only for having a "cool fade in animation that I like and it fits the design".

I want at least a fallback color!!

Don't do that either. If you're using a progressive image then the time a browser might show the "ugly alt text" is greatly reduced. Automating a fallback background color is not worth the extra code or complexity. Besides it can get in the way with alpha transparency images anyway.

Conclusion

Embrace the simpliness that you now have and put your mind into other things.

Top comments (2)

Collapse
 
merri profile image
Vesa Piittinen

I guess Lighthouse recommends WebP because both are Google's.

Since there is no progressive option with WebP you can only take the hit. But you could add AVIF which allows for even smaller file sizes with good quality, and I think they added thumbnail support to the standard so you can get some kind of equivalent to progressive loading.

Also JPEG XL is coming which does support progressive and is responsive by design, and apparently can losslessly take in original JPEG but still achieves smaller file size for it. And can losslessly transfrom back to JPEG. Magical stuff.