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

前端 未结 14 1182
轻奢々
轻奢々 2020-11-21 06:25

I want to do:

$(\"img\").bind(\'load\', function() {
  // do stuff
});

But the load event doesn\'t fire when the image is loaded from cache

14条回答
  •  太阳男子
    2020-11-21 07:17

    I just had this problem myself, searched everywhere for a solution that didn't involve killing my cache or downloading a plugin.

    I didn't see this thread immediately so I found something else instead which is an interesting fix and (I think) worthy of posting here:

    $('.image').load(function(){
        // stuff
    }).attr('src', 'new_src');
    

    I actually got this idea from the comments here: http://www.witheringtree.com/2009/05/image-load-event-binding-with-ie-using-jquery/

    I have no idea why it works but I have tested this on IE7 and where it broke before it now works.

    Hope it helps,

    Edit

    The accepted answer actually explains why:

    If the src is already set then the event is firing in the cache cased before you get the event handler bound.

提交回复
热议问题