使用模糊预览预加载图像

时间:2016-09-12 15:13:06

标签: javascript jquery css facebook image

我有两个版本的图片:全分辨率图片(大分辨率,高质量)和预览图片(小分辨率,低质量Q10,高压缩,非常小~1kb)。

要预先加载图片,我尝试在这里发布Facebook所做的事情https://code.facebook.com/posts/991252547593574/the-technology-behind-preview-photos/:在图片容器中放置一个小图片版本并将其放大并应用CSS模糊。这用作预览,其中用户获得对图像的粗略印象。然后,通过JS加载原始图片,并在完成加载后交换图像。

这是我的代码:

http://plnkr.co/edit/SVUMGCmtTrHJnZXnBVXu?p=preview

<style>
  .container {
    width: 500px;
    height: 300px;
    -webkit-transform: translate3d(0, 0, 0);
    overflow: hidden;

  }
  .myImage {
    width: 500px;
    height: 300px;
    background-position: center;
    background-size: cover;
  }

  .preview {
    filter: blur(10px);
    -webkit-filter: blur(10px);
  }
</style>

<div class="container">
  <div class="myImage preview" 
    data-image-url="http://oi67.tinypic.com/2jfhwck.jpg" 
    style="background-image: url(http://i67.tinypic.com/2jfhwck_th.jpg);">
  </div>
</div>

<script>
  function imgComplete(img) {
    return img.complete || img.width + img.height > 0;
  }

  function removePreview(container, url) {
    container.css({'background-image': 'url("' + url + '")'});
    container.removeClass('preview');
  }

  $('.preview').each(function(idx, container) {
    container = $(container);
    var url = container.data('image-url');
    var img = new Image();
    img.src = url;

    // if we have this image already cached, we don't have
    // to wait for the onload callback and can remove the
    // preview image immediately
    if(imgComplete(img)) {
      removePreview(container, url);
    } else {
      img.onload = function() {
        removePreview(container, url);
      };
    }
  });
</script>
  

问题在于闪烁:第一次加载图像时,它会显示模糊的预览,加载大图像后,它会被交换。然后,当您重新加载页面时,您已经在浏览器中缓存了大图像,并且它不应显示模糊版本。但是,您可以在短时间内看到它。 p>      

如果有任何想法,如何防止模糊预览图像的闪烁,并立即显示图像的大分辨率,如果它已经在浏览器缓存中了?

0 个答案:

没有答案
相关问题