简体   繁体   中英

jQuery IE doesn't fire load event

I'm having an issue when it comes to showing images once they've loaded. The effect I want is to show a loading .gif behind the image and when it's loaded fade it in. The following code works for any images I load in via AJAX, however on page load I'd like the same effect.

$(function() {
    $("#products img").hide().bind("load", function() {
        $(this).fadeIn(300);
    });
});

Note, this works nicely in all browsers except IE (only tested 9). From what I understand it's not firing the load event because either the image is cached or the image has loaded before the event has been binded. I want the browser to cache images so adding a date/time stamp to the end of the image src is not really an option.

Is there a way I can say If the image is already loaded in some form or another, show it. Otherwise hide it and fade it in once it's loaded. If the image is already loaded in some form or another, show it. Otherwise hide it and fade it in once it's loaded. ?

Edit: I tried setting up a fiddle but it didn't really like it. Here it is anyway if it's helpful

Edit

If anyone is interested I've put up a quick js performance test for the two answers. 在此处输入图片说明
(source: grabilla.com )

I had the same problem and solved it like this:

 $("#products img").one('load.FadeIn', function () {
     $(this).fadeIn(300);
 });

 $("#products img").trigger('load.FadeIn');

Either image has already been loaded and fades in or we manually trigger the event.

You could add a filter which passes only images which haven't yet been loaded:

$("#products img")
  .filter(function(i, img) { return ! img.complete })
  .hide()
  .bind("load", function() {
    $(this).fadeIn(800);
  });

demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM