6

Currently, images with the attribute loading="lazy" (https://web.dev/native-lazy-loading/) are displayed immediately when loaded, i.e. without fade-in effect.

Is there a way to animate images with the loading="lazy" attribute when they are loaded and preferably without JavaScript?

I know, there are many lazyloading JavaScript libraries, but just because loading is now done natively by the browser, the handling via JavaScript feels like a step back again.

Mosh Feu
  • 28,354
  • 16
  • 88
  • 135
kimomat
  • 2,211
  • 23
  • 37

2 Answers2

6

I managed to use a simple jQuery solution, since its already used in my case:

 //fade in lazy loaded images
 $('article img').on('load', function(){
    $(this).addClass('loaded');
 });

The images have 0 opacity by default and opacity 1 from the new class

img{
    opacity: 0;
    transition: opacity 300ms ease-in-out;
}

img.loaded{
    opacity: 1;
}

This is not graceful as users w/o JS wont see the images ... but frankly i don't care ^^ To be honest, who has JS disabled?

  • 3
    Thanks, this could be a progressive way. For disabled JS Users, you could initially add a no-js class and change the class to js if js is enabled. Like modernizr does. (https://github.com/Modernizr/Modernizr/blob/master/src/setClasses.js#L23) – kimomat Jul 27 '20 at 07:40
  • 1
    Something like :loaded pseudo would be nice in css in the future. – BritishSam May 10 '22 at 09:54
  • This is a really neat solution but on testing it, I see it doesn't work on images which are initially visible. When scrolling, the images do indeed fade in nicely but the images in the header remain at opacity: 0. – Dave Jun 05 '22 at 17:32
0

Unfortunately it is not as simple as the simple jQuery solution above. .on('load') does not work properly for all Browsers (like Chrome) as discussed here: Check if an image is loaded (no errors) with jQuery

Balduin
  • 51
  • 5