jQuery Ajax等到所有图像都加载完毕

时间:2011-01-23 16:00:18

标签: jquery ajax loading

我正在尝试使用运行良好的jQuery执行Ajax调用。我使用success事件来显示数据。但是,只要加载外部HTML文件,就会触发成功。如果有大图像,它们会在显示后继续加载。有什么方法可以在所有内容完全加载后显示内容吗?这是代码:

$('#divajax').html('<br><div style="text-align: center;"><img src="res/ajax-loader.gif"></div>');
$.ajax({
    cache: false,
    url: 'ajax/content.php',
    success: function(data) {
          $('#divajax').html(data);
    }
});

10 个答案:

答案 0 :(得分:46)

@alex编写的插件由于某种原因并没有为我工作......我无法弄清楚原因。但他的代码确实激励我提出一个更适合我的轻量级解决方案。它使用jquery承诺。请注意,与@alex的插件不同,这并不会尝试考虑元素上的背景图像,只考虑img元素。

// Fn to allow an event to fire after all images are loaded
$.fn.imagesLoaded = function () {

    // get all the images (excluding those with no src attribute)
    var $imgs = this.find('img[src!=""]');
    // if there's no images, just return an already resolved promise
    if (!$imgs.length) {return $.Deferred().resolve().promise();}

    // for each image, add a deferred object to the array which resolves when the image is loaded (or if loading fails)
    var dfds = [];  
    $imgs.each(function(){

        var dfd = $.Deferred();
        dfds.push(dfd);
        var img = new Image();
        img.onload = function(){dfd.resolve();}
        img.onerror = function(){dfd.resolve();}
        img.src = this.src;

    });

    // return a master promise object which will resolve when all the deferred objects have resolved
    // IE - when all the images are loaded
    return $.when.apply($,dfds);

}

然后你可以使用这样的东西:

$.ajax({
    cache: false,
    url: 'ajax/content.php',
    success: function(data) {
        $('#divajax').html(data).imagesLoaded().then(function(){
            // do stuff after images are loaded here
        });
    }
});

希望这对某人有帮助。

请注意,使用上面的代码,如果其中一个图像错误(例如因为URL错误),则无论如何都会解析承诺并忽略错误。这可能是您想要的,但是,根据您的情况,您可能会想要在图像无法加载时中止您正在执行的操作。在这种情况下,您可以按如下方式替换onerror行:

img.onerror = function(){dfd.reject();}

并抓住这样的错误:

$('#divajax').html(data).imagesLoaded().done(function(){
    // do stuff after all images are loaded successfully here
}).fail(function(){
    // do stuff if any one of the images fails to load
});

答案 1 :(得分:17)

您可以使用我的jQuery插件waitForImages ...

$.ajax({
    cache: false,
    url: 'ajax/content.php',
    success: function(data) {

         $('#divajax').html(data).hide().waitForImages(function() {
             $(this).show();
         });

    }
});

这将把东西加载到你的元素中,隐藏它,然后在加载后代img元素时重新显示它。

答案 2 :(得分:10)

您可以将某些内容绑定到加载事件,以了解它们何时完成:

$('<img>').bind('load', function() {
    $(this).appendTo('body');
});

或者您可以使用this plugin

答案 3 :(得分:4)

这会分别触发每个img加载:

$('img').on('load', function() {
      // do something
});

我用过:

var loaded = 0;
$('img').on('load', function() {
   loaded++;
   if(loaded == $('img').length){
      // do something
   }
});

答案 4 :(得分:2)

您可以使用与JavaScript和jQuery一起使用的imagesloaded插件,尝试在加载的内容上使用ajax success回调函数,并在imagesloaded回调函数不触发时隐藏所有内容,见下面的示例代码

$.ajax({
    cache: false,
    url: 'ajax/content.php',
    success: function(data) {
        var $divajax = $('#divajax').html(data).hide();
        $divajax.imagesLoaded(function() {
             $divajax.show();
         });

    }
});

答案 5 :(得分:0)

使用jquery的.load()

其中有一个描述:

  

当加载事件和所有子元素已完全加载时,会将事件发送到元素。此事件可以发送到与URL关联的任何元素:图像,脚本,框架,iframe和窗口对象。

答案 6 :(得分:0)

$('#divajax').html('<br><div style="text-align: center;"><img src="res/ajax-loader.gif"></div>').load(function() {
$.ajax({
    cache: false,
    url: 'ajax/content.php',
    success: function(data) {
          $('#divajax').html(data);
    }
});
});

答案 7 :(得分:0)

试试这段代码。它工作正常。

$.ajax({
    url: "../api/listings",
    type: 'GET',
    success: function (html) {
        $('#container').append(html);
        $('#container img').on('load', function(){console.log('images loaded')});
    };
});

答案 8 :(得分:0)

当Daniel的解决方案没有找到图片时,我遇到了一个小错误。

以防其他人遇到同样的问题:

变化:

// if there's no images, just return an already resolved promise
if (!$imgs.length) {return $.Deferred.resolve().promise();}

致:

// if there's no images, just return an already resolved promise
    if (!$imgs.length) {
        var dfd = $.Deferred();
        return dfd.resolve().promise();
    }

答案 9 :(得分:-6)

我认为最好的是使用此

$(window).ready(function(){ //load your ajax})
相关问题