Know when images are done loading in AJAX response

核能气质少年 提交于 2019-11-28 21:34:50

You need to add the load handler in the AJAX callback in order to have it apply to the images that are being loaded via the AJAX call. You may also want to have a timer set to show the content after some interval in case the images get loaded before the load handler is applied.

$.ajax({
     ...
     success: function(data) {
          var imageCount = $(data).filter('img').length;
          var imagesLoaded = 0;
          $(data).hide()
                 .appendTo('#someDiv')
                 .filter('img')
                 .load( function() {
                     ++imagesLoaded;
                     if (imagesLoaded >= imageCount) {
                        $('#someDiv').children().show();
                     }
                  });
          setTimeout( function() { $('#someDiv').children().show() }, 5000 );
      }
});
bgreater

This is an updated version of the code tvanfosson provided.

You have to make sure the imageCount variable is counting a node list and not a string as was the problem in the original code from I can deduce:

$.ajax({
    url      : 'somePage.html',  
    dataType : "html",
    success  : function(data) {

        $(data).hide().appendTo('#someDiv');

        var imagesCount = $('#someDiv').find('img').length;
        var imagesLoaded = 0;

        $('#someDiv').find('img').load( function() {
            ++imagesLoaded;
            if (imagesLoaded >= imagesCount) {
                $('#someDiv').children().show();
            }
        });

        var timeout = setTimeout(function() {
            $('#someDiv').children().show();
        }, 5000);
    }                     
});
mahemoff

$("img").load() won't work because the images are loaded dynamically; that command will only apply to images on the page at the time.

use $("img").live("load") to track when the images have loaded.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!