Lazysizes: Fire an event right after image is loaded

Created on 12 Feb 2016  路  5Comments  路  Source: aFarkas/lazysizes

@aFarkas I might have overlooked something in the documentation, but I think it would be handy to fire an event right after the image is loaded so that some other actions could be performed.
In my case there is a little preloader element that I would like to remove right after a given image is loaded.
I could achieve it by adding triggerEvent(e.target, 'lazyImageLoaded'); to switchLoadingClass:

        var switchLoadingClass = function(e){
            addClass(e.target, lazySizesConfig.loadedClass);
            removeClass(e.target, lazySizesConfig.loadingClass);
            addRemoveLoadEvents(e.target, switchLoadingClass);
            triggerEvent(e.target, 'lazyImageLoaded');
        };

I then listen to that event and then trigger the relevant function:

            document.addEventListener('lazyImageLoaded', function(e){
                that.removeGifPreloader(e.target);
            });

Maybe an option in config afterLoadEvent or similar could work? What do you think?

Most helpful comment

You can use the standard load event on the image for this problem...

const imgs = document.querySelectorAll('img');

if (imgs === null) {
  return;
}

Array.from(imgs).forEach(img => {
  img.addEventListener('load', () => {
    // Do what you need to do...
  });
});

All 5 comments

You can use the standard load event on the image for this problem...

const imgs = document.querySelectorAll('img');

if (imgs === null) {
  return;
}

Array.from(imgs).forEach(img => {
  img.addEventListener('load', () => {
    // Do what you need to do...
  });
});

I'd say this issue can be closed.

Edit: My apologies. @simplenotezy said below:

that won't work for background images.

No @maketimetodesign - that won't work for background images.

Plus one eventlistener is better than 100's.

Was this page helpful?
0 / 5 - 0 ratings