How to call a onload callback on webp images load?

323 Views Asked by At

As we know, we could call a onLoad callback on img elements for images load. like what I did for it:

var i = new Image();
if (crossOrigin) i.crossOrigin = crossOrigin;

i.onload = function () {
  decode && i.decode ? i.decode().then(resolve)["catch"](reject) : resolve();
};

i.onerror = reject;
i.src = src;

But if I use avif or webp formats with picture tag, how could I wait for load event? sth like:

<picture>
    <source srcset="img/photo.avif" type="image/avif">
    <source srcset="img/photo.webp" type="image/webp">
    <img src="img/photo.jpg" alt="Description of Photo">
</picture>
1

There are 1 best solutions below

0
On

There are multiple approaches. You can use a library or you could use the IntersectionObserver API and add the needed feature.

Rather than repeating things, the SO post here has some inputs which you may adopt as needed.

https://stackoverflow.com/a/54092875/34644