jQuery的阿贾克斯等到所有图像都加载 [英] jQuery Ajax wait until all images are loaded

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

问题描述

我试图执行一个Ajax调用使用jQuery这是运作良好。我用的是成功事件中显示的数据。这似乎然而,成功获取,一旦外部HTML文件被加载触发。如果有大量的图像,他们继续加载它们显示后。有没有一种方法来显示内容都满载后?这里是code:

  $('#divajax)HTML('< BR>< D​​IV的风格=文本对齐:中心;>< IMG SRC =RES / AJAX-loader.gif>< / DIV>');
$阿贾克斯({
    缓存:假的,
    网址:AJAX / content.php',
    成功:功能(数据){
          $('#divajax')的HTML(数据)。
    }
});
 

解决方案

这@alex写的我没有工作,出于某种原因,插件...我想不出为什么。但他的code也激励我拿出一个是为我工作更轻量级的解决方案。它使用jQuery的承诺。请注意,不像@alex的插件,这并不试图解释上的元素背景图像,只的img要素。

  // Fn键允许事件触发后,所有图像都加载
$ .fn.imagesLoaded =功能(){

    //编辑:在严格模式下,var关键字是必要的
    变量$ IMGS = this.find('IMG [SRC =!]');
    //如果没有图片,只是返回一个已经解决的承诺
    如果(!$ imgs.length){返回$ .Deferred()解析()的承诺();}

    //为每个图像,延期对象添加到当图像被加载它解决了数组(或加载失败)
    VAR DFDS = [];
    $ imgs.each(函数(){

        变种DFD = $ .Deferred();
        dfds.push(DFD);
        VAR IMG =新的图像();
        img.onload =功能(){dfd.resolve();}
        img.onerror =功能(){dfd.resolve();}
        img.src = this.src;

    });

    //返回主许诺的对象,这将解决,当所有的延期对象已解决
    // IE浏览器 - 当所有的图像加载
    返回$ .when.apply($,DFDS);

}
 

然后你可以使用它是这样的:

  $。阿贾克斯({
    缓存:假的,
    网址:AJAX / content.php',
    成功:功能(数据){
        $('#divajax)。HTML(数据).imagesLoaded(),然后(函数(){
            //做的东西在这里都加载图像后
        });
    }
});
 

我希望这是对别人有帮助的。

请注意,使用上述code,如果图像错误之一(例如,因为URL是错误的),许是无论如何解决,忽略错误。这可能是你想要的,但是,根据您的情况,您可能反而要中止不管你在做什么,如果图像无法加载。在这种情况下,你可以更换的onerror行,如下所示:

  img.onerror =功能(){dfd.reject();}
 

和捕获的错误是这样的:

  $('#divajax)。HTML(数据).imagesLoaded()。完成(功能(){
    //做的东西后,加载成功在这里的所有图像
}),失败(函数(){
    //做的东西,如果图像中的任何一个加载失败
});
 

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

解决方案

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 () {

    // Edit: in strict mode, the var keyword is needed
    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
        });
    }
});

Hopefully that's helpful for someone.

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

And catch the error like this:

$('#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的阿贾克斯等到所有图像都加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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