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

前端 未结 14 1210
轻奢々
轻奢々 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:23

    Can I suggest that you reload it into a non-DOM image object? If it's cached, this will take no time at all, and the onload will still fire. If it isn't cached, it will fire the onload when the image is loaded, which should be the same time as the DOM version of the image finishes loading.

    Javascript:

    $(document).ready(function() {
        var tmpImg = new Image() ;
        tmpImg.src = $('#img').attr('src') ;
        tmpImg.onload = function() {
            // Run onload code.
        } ;
    }) ;
    

    Updated (to handle multiple images and with correctly ordered onload attachment):

    $(document).ready(function() {
        var imageLoaded = function() {
            // Run onload code.
        }
        $('#img').each(function() {
            var tmpImg = new Image() ;
            tmpImg.onload = imageLoaded ;
            tmpImg.src = $(this).attr('src') ;
        }) ;
    }) ;
    

提交回复
热议问题