使用jQuery重新加载多个图像?如何优化

Reload multiple images using jQuery? How to optimize?

本文关键字:图像 何优化 优化 jQuery 新加载 加载 使用      更新时间:2023-09-26

我使用jQuery:更新了多个图像

window.onload = function () {
    setInterval(function () {
        $(".image").each(function (index) {
            base_url = $(this).attr('src').split('?rand=')[0];
            address = base_url + '?rand=' + Math.random();
            $(this).attr("src", address);
        });
    }, 10000);
};

我正在努力改进它:

function update() {
    setInterval(function () {
        $(".cameragrid_").find("img").each(function (index) {
            d = new Date();
            var src = $(this)[0].src;
            var state = $(this).context.readyState;
            if (state == 'complete'); {
                $(this).attr("src", src + d.getTime());
            }
        });
        console.log('click');
    }, 10000);
}
$(window).ready(function () {
    $('.cameragrid_').hide();
});
$(window).load(function () {
    $('.cameragrid_').show();
    update();
});

我想把时间从10秒减少到3秒,但当我减少这个时间时,不要更新所有的图像,我的算法和其他的都不会更新。.

有什么方法可以优化它在3秒内运行吗?

与其为多个图像设置一个计时器,不如尝试为每个图像或至少一小批图像设置多个计时器。

window.onload = function () {
    $(".image").each(function (index) {
        setInterval(function () {
             base_url = $(this).attr('src').split('?rand=')[0];
             address = base_url + '?rand=' + Math.random();
             $(this).attr("src", address);
        }, 3000);
    });
};

我还没有测试过这段代码,但你可以理解,也许你必须在某个地方添加一个$.proxy()来修复这个上下文。

通过这种方式测试图像是否被显示应该更容易:https://www.customd.com/articles/13/checking-if-an-element-is-visible-on-screen-using-jquery

嘿,你试过了吗https://tinypng.com/这压缩了图像格式,这将增加图像的一些加载时间。你也可以通过这种方式将10个图像的精灵变成1,只加载一个文件,然后对精灵进行索引。

从未亲自尝试过image min,但这也值得一看。

相信精灵可以在镜头中解决你的问题。

我以这种方式结束:

setInterval(function(){
                $( ".image" ).each(function( index ) {
                    var img = new Image();
                    img.src = $(this).attr('src');
                    if(img.complete){
                    base_url = $(this).attr('src').split('?rand=')[0];
                    address = base_url + '?rand=' + Math.random();
                    $(this).attr("src", address);
                    }
                });
            },500);