当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Pre load images from an ajax request before displaying them?

问题描述:

I'm using jQuery to load html content which contains images, the problem is that i don't want the effect of blinking on images due to loading, to achieve that i need to pre load images inside the response body before inserting it to guarantee a smooth update.

Current Code:

$.ajax({

url: 'hello.php',

method: 'GET',

data:'id='+id,

success: function(data) {

$('#section').html(data);

}

});

Any Solutions?

Thanks

网友答案:

I use the the jQuery onImagesLoad plugin for this.

网友答案:

You could try something like this (untested):

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

Works fine when I tried it.

分享给朋友:
您可能感兴趣的文章:
随机阅读: