1

I want to console.log the src attribute of any image constructed via the Image constructor on my web page. I don’t need the image when it’s loaded - just after the src attribute changes.

I’ve tried overriding the Image.onload method (This method of course gives me the later point at which the image has already loaded), but this code doesn’t console.log anything:

Image.prototype.nativeOnload = Image.prototype.onload;
Image.prototype.onload  = function() {
  console.log(this.src);
  this.nativeOnload();
};

Perhaps this is because the onload property is overridden.

How can I detect when any image on the web page constructed via the js Image() constructor changes its source? Is there a way to do this with javascript watchers perhaps?

John Hoffman
  • 17,857
  • 20
  • 58
  • 81

1 Answers1

1

FIRST OPTION

the easiest (and less overhead) way would be to implement a callback in the code that changes the source of an image tag. However for this you need access to de code and must be able to change it.

SECOND OPTION

you also could define a DOM eventlistener but not all browsers support this.

DOMAttrModified

A previous question on stackoverflow is about this option.

THIRD OPTION

The third method for accomplishing this is by checking the source of the image periodically and see if it's changed since the previous check. you can do this with an interval.

jsfiddle demo (click the "change source" button or even try to change the source in firebug to test this)

html

<img id="check" src="yourimagesource">

js

var check_img=$("#check");
var current_src=check_img.attr("src");


window.setInterval(function(){
    new_src=check_img.attr("src");
    if(current_src!=new_src){
        alert("src changed");
        current_src=new_src;
    }

}, 500);
Community
  • 1
  • 1
kasper Taeymans
  • 6,950
  • 5
  • 32
  • 51
  • Thanks - but I don't actually have access to the individual image elements. External libraries construct them in private methods ... – John Hoffman Jan 08 '15 at 19:30
  • ok so adding callbacks won't be an option then. however you could implement the other proposed methods. ps: updated jsfiddle – kasper Taeymans Jan 08 '15 at 19:35