13
<img src="http://site.com/image.png" />

I change src of this image on .click event.

There can be loaded more than 20 different images, after changing src.

1) How do I know, was image already loaded (should be cached) or it has to be loaded?

2) How to run two different functions, for loaded and not?

Thanks.

James
  • 42,081
  • 53
  • 136
  • 161
  • Also see this question: http://stackoverflow.com/questions/1948672/how-to-tell-if-an-image-is-loaded-or-cached-in-jquery – J. Taylor Mar 13 '11 at 22:16
  • Possible duplicate of [Browser-independent way to detect when image has been loaded](https://stackoverflow.com/questions/821516/browser-independent-way-to-detect-when-image-has-been-loaded) – Liam Jun 26 '17 at 09:25

1 Answers1

22

You need to attach an event handler for the load event:

Update 2017:

$('img').on('load', function() {
    alert('new image loaded: ' + this.src);
});

Plain JS/DOM:

imgNode.onload = () => {
    alert('new image loaded: ' + this.src);
};
jAndy
  • 231,737
  • 57
  • 305
  • 359
  • how to run two different functions, for loaded and not? – James Mar 13 '11 at 22:16
  • @Happy: this event is fired regardless if the image is loaded from a server or the browser cache. I'm not aware of a possiblity to distinct between the two. – jAndy Mar 13 '11 at 22:19
  • 1
    Note that as of jQuery 1.7, .on() is preferred to .bind() The rest of the code is the same :) – Spinal Aug 20 '14 at 09:54
  • This answer could really use an update. `bind()` has been superseded and deprecated for sometime now. – Liam Jun 26 '17 at 09:29