jQuery图像交换不立即显示

时间:2015-07-23 01:17:04

标签: javascript jquery image

我正在使用下面的jQuery代码替换部分图像src。基本上它将 example.com/200x200/sample.jpg 转换为 example.com/500x500/sample.jpg

它工作得很好唯一的问题是它在显示新图像之前先渲染旧图像。是否可以先加载交换图像以改善用户体验?

$(document).ready(function() {
    $(".gallery img").each(function() {
        $(this).attr("src", function(a, b) {
            return b.replace("200x200", "500x500")
        })
    })
});

JSFiddle Demo (单击“多次运行”)

3 个答案:

答案 0 :(得分:0)

将图像放在隐藏溢出且高度和宽度为0的固定位置div中。这将导致图像加载但不显示。这是一个显示基本思想的小提琴:https://jsfiddle.net/0tm3kb6e/。 10秒后显示此图像。使用chrome来限制网络,您将看到它在显示时加载。这是我使用的代码。你只需要html和css

HTML

<div id="image-hider">
  <img src="https://www.google.com/images/srpr/logo11w.png"/>
</div>

CSS

#image-hider {
  height:0;
  width: 0;
  overflow: hidden;
  position: fixed;
}

的javascript

$(document).ready(function() {
  setTimeout(function() {
    $('#image-hider').css('height','500px');
    $('#image-hider').css('width','500px');
  }, 10000);
});

答案 1 :(得分:0)

这应该可以解决您的问题,(连续多次点击运行来测试它或者看一下片段下面的小提琴)

<强>段:

$(document).ready(function() {
  function preload(newImage) {
    $(newImage).each(function() {
      (new Image()).src = this;
    });
  }
  preload([
    '//lorempixel.com/500/500'
  ]);
  $(".gallery img").each(function() {
    $(this).attr("src", function(a, b) {
      return b.replace("200/200", "500/500");
    });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="gallery">
  <img src="//lorempixel.com/200/200" />
</div>

Fiddle

答案 2 :(得分:0)

尝试使用叠加div

<div class="gallery">
    <img src="//lorempixel.com/200/200" />
    <div class="overlaydiv"> </div>
</div>

在一秒钟后隐藏它(为图像加载一段时间)

 $(".gallery img").each(function () {
     $(this).attr("src",$(this).attr("src").replace("200/200", "400/400"));
     setTimeout(function(){            
     $(".overlaydiv").hide();
     },1000);
 });

查看此fiddle