在显示之前从ajax请求预加载图像?

时间:2010-12-10 23:56:21

标签: javascript jquery

我正在使用jQuery来加载包含图像的html内容,问题是我不希望因加载而导致图像闪烁的效果,以实现我需要在插入之前预先加载响应体内的图像这是为了保证顺利更新。

当前代码:

$.ajax({
url: 'hello.php',
method: 'GET',
data:'id='+id,
success: function(data) {
$('#section').html(data);               
}
});

任何解决方案?

由于

2 个答案:

答案 0 :(得分:0)

我使用了jQuery onImagesLoad plugin

答案 1 :(得分:0)

您可以尝试这样的(未经测试)

var imagesLoading = 0;

$.ajax({
    url: 'hello.php',
    method: 'GET',
    data: 'id=' + id,
    success: function(data) {
        imagesLoading = 0;

        $(data).filter('img').each(function() {
            imagesLoading++;

            var image = new Image();

            image.onload = function() {
                imagesLoading--;
                if(imagesLoading == 0) {
                    $('#section').html(data);
                }
            };

            image.src = $(this).attr('src');
        });
    }
});

我尝试时工作正常。