-1

I have an image in dom like below:

<img id="myImg" src="https://upload.wikimedia.org/wikipedia/commons/c/cf/Frog_on_river_4000x3000_26-09-2010_11-01am_2mb.jpg"> </img>

i am trying get a console information when image is completely loaded. so i wrote something below:

document.querySelector("img").onload = function() {
  console.log('new image loaded: ' + this.getAttribute("src"));
};

unfortunately it is not working the way i expect. i also tried jQuery load function but it is removed now so what is wrong with this code or what am i missing?

  • You can check this https://stackoverflow.com/questions/263359/how-can-i-determine-if-an-image-has-loaded-using-javascript-jquery – Aman Sep 09 '17 at 10:24
  • Possible duplicate of [Check if an image is loaded (no errors) in JavaScript](https://stackoverflow.com/questions/1977871/check-if-an-image-is-loaded-no-errors-in-javascript) – Axel Sep 09 '17 at 10:25

3 Answers3

1

First, images have self closing tags so no need for </img>, just <img ... />. Second, use querySelectorAll to get all images, and for each image, add the onload event listener:

var imgs = document.querySelectorAll("img");
imgs.forEach((img) => 
    img.onload = function() {
        console.log('new image loaded: ' + this.getAttribute("src"));
    }
);
<img id="myImg" src="https://upload.wikimedia.org/wikipedia/commons/c/cf/Frog_on_river_4000x3000_26-09-2010_11-01am_2mb.jpg"/>
<img id="myImg2" src="http://placeskull.com/600/600"/>
<img id="myImg3" src="http://placeskull.com/300/300"/>
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
0

Try this :

<img src="https://upload.wikimedia.org/wikipedia/commons/c/cf/Frog_on_river_4000x3000_26-09-2010_11-01am_2mb.jpg">

var img = document.querySelector('img').getAttribute('src');
console.log('img', img);
Chandru
  • 10,864
  • 6
  • 38
  • 53
0

That's because the onload event will not fire for cached items.

Bekim Bacaj
  • 5,707
  • 2
  • 24
  • 26