Jitin Maherchandani
Jitin Maherchandani

Reputation: 687

How to Catch Image Load event on an Image getting Loaded Multiple times on the same page?

I have a Dynamically changing Page in which images are inserted at sometime or other. I want to know each instance of time the image (with given img src,alt attribute) gets loaded on this page.

**PS-There can be any number of Images(of same type) present on the page . The images are not cached, they are dynamically getting inserted inside the page .

$("img").one("load", function() {
  // do stuff
}).each(function() {
  if(this.complete) $(this).load();
});

The above code sample doesnot work for me.

**

Upvotes: 1

Views: 614

Answers (1)

Parag Bhayani
Parag Bhayani

Reputation: 3330

Here you can do one thing, you can register an event of DOMNodeInserted which will be fired when any DOM Node is added in the page. then you can check that if added element is img or not. if it image then you can register onload event on it.

$(document).on('DOMNodeInserted', function(event) {
  console.log($(event.target).is('img'));
  if($(event.target).is('img')) {
    $(event.target).one("load", function() {
      // do stuff
      console.log("one", arguments)
    });
  }
});

example load of image

$('body').append($("<img src='http://www.freedomwallpaper.com/nature-wallpaper/nature-hd-wallpapers-water.jpg'>"))

This will handle your on image load kind of thing...

You need to check that whether is called everytime or if parentNode contains chalidNode then how it is being handled ... but you might need to look this in detail...

Another option would be to use setInterval function which is called ever 1000 miliseconds and check for any DOM change... and you can check that which images are loaded or not i.e.

setInterval(function() {
    $.each($('img'), function(index, image) {
      console.log(image.complete)
    });
}, 1000)

And you may go ahead with this approach...

Upvotes: 1

Related Questions