jQuery Ajax 等待所有图像加载完毕 [英] jQuery Ajax wait until all images are loaded

查看:31
本文介绍了jQuery Ajax 等待所有图像加载完毕的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用运行良好的 jQuery 执行 Ajax 调用.我使用成功事件来显示数据.然而,一旦加载外部 HTML 文件,似乎就会触发成功.如果有大图像,它们会在显示后继续加载.有没有办法在所有内容完全加载后显示内容?代码如下:

I'm trying to perform an Ajax call with jQuery which is working well. I use the success event to display the data. It seems however that success gets triggered as soon as the external HTML file gets loaded. If there are large images they keep loading after they're shown. Is there a way to display the content after everything is fully loaded? Here is the code:

$('#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);
    }
});

推荐答案

@alex 编写的插件由于某种原因对我不起作用......我不知道为什么.但他的代码确实激励我想出一个更适合我的轻量级解决方案.它使用 jquery 承诺.请注意,与@alex 的插件不同,这不会尝试考虑元素上的背景图像,仅考虑 img 元素.

The plugin that @alex wrote didn't work for me for some reason... I couldn't figure out why. But his code did inspire me to come up with a more lightweight solution that is working for me. It uses jquery promises. Please note that unlike @alex 's plugin, this doesn't attempt to account for background images on elements, only img elements.

// 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);

}

然后你可以像这样使用它:

Then you can use it something like this:

$.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 行:

Note that using the above code, if one of the images errors (eg because the URL was wrong), the promise is resolved anyway and the error is ignored. This might be what you want, but, depending on your situation, you might instead want to abort whatever you are doing if an image fails to load. In which case you could replace the onerror line as follows:

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
});

这篇关于jQuery Ajax 等待所有图像加载完毕的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆