开发者

Pre load images from an ajax request before displaying them?

开发者 https://www.devze.com 2023-01-29 19:18 出处:网络
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 re

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 C开发者_JAVA百科ode:

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

0

精彩评论

暂无评论...
验证码 换一张
取 消