3

how to handle onLoad Event on img tag?

example:

$ ('img'). onload (function (e) {
   alert ('image loaded' + $ (this), attr ('src'));
})

is like the imageLoader

and others tags like script, link, etc...

basicxman
  • 2,077
  • 14
  • 21
rkmax
  • 15,852
  • 22
  • 82
  • 170

3 Answers3

5

jQuery callback on image load (even when the image is cached)

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

Seems to work for me, and should fix the caveat with caching.

Community
  • 1
  • 1
Joe
  • 15,062
  • 4
  • 38
  • 77
3

There's an example of how to do this right on the jQuery doc page for .load().

HTML:

<img src="book.png" alt="Book" id="book" />

Javascript:

$('#book').load(function() {
  // Handler for .load() called.
});

And, there are a bunch of caveats to watch out for listed on that jQuery page too.

With images, if you want to assure that the load handler gets called, the load handler has to be set before the image can possibly be loaded. If you're constructing the image in code, that means you have to set the load handler before you set the .src attribute. That's because, in some browsers, if the image is in the memory/disk cache, it will load immediately when you assign .src and if you then subsequently set the .load() handler, you will be too late (the image will already be loaded) and the .load() handler will never be called.

I don't know how to guarantee that a jQuery-based .load() always gets called for an image that's in your page HTML because you can't assign the event handler until the object exists, but once the object it exits, it might already be loaded. You can use non-jQuery setting of an onload=xxx in the actual HTML though that is an older style of coding. Of course, you can always hook window.onload to know when all page images (and other resources) have been loaded.

jfriend00
  • 580,699
  • 78
  • 809
  • 825
  • please @jfriend00 read the section: Caveats of the load event when used with images – rkmax Sep 09 '11 at 00:46
  • I've read the caveats. I don't know why they sound so pessimistic unless jQuery's implementation is buggy. I've used the load event (non-jQuery, plain-javascript-based) with images in code that runs reliably on thousands of sites (in code that runs a slideshow so the code knows when the next image is loaded and ready for display) and all sorts of browsers from IE6 on up. I have never had problems with it. You do have to make sure that the event hasn't already fired, but there are ways to detect/prevent that. – jfriend00 Sep 09 '11 at 00:54
0

jQuery has a load method, not onload. And your code should probably be:

$ ('img').load(function () {
   alert('image loaded ' + this.src);
})
RobG
  • 124,520
  • 28
  • 153
  • 188