Lazysizes srcset图像让浏览器在图像加载之前确定总页面大小

时间:2016-04-05 18:31:50

标签: css twitter-bootstrap lazy-loading srcset responsive

我在流畅的布局上使用lazysizes插件和srcset一起使用。我无法弄清楚如何让浏览器将页面加载到正确的长度,而不是在滚动时扩展页面。

我使用bootstrap框架在这里演示了一个codepen

http://codepen.io/elevenelevne/pen/EKbERV

经过多次阅读我确定这是因为浏览器无法计算高度,因为它没有设置,但我不能让它以响应的方式工作

代码,但比如10行

<div class="container-fluid">

  <div class="row-fluid">

    <div class="col-xs-12 col-sm-6">
      <img data-sizes="auto" data-src="http://placehold.it/160x107" data-srcset="http://placehold.it/320x231 640w, http://placehold.it/640x426 1280w, http://placehold.it/1000x666 2000w, http://placehold.it/2500x1666 4000w" class="img-responsive lazyload" />
    </div>

    <div class="col-xs-12 col-sm-6">
      <img data-sizes="auto" data-src="http://placehold.it/160x107" data-srcset="http://placehold.it/320x231 640w, http://placehold.it/640x426 1280w, http://placehold.it/1000x666 2000w, http://placehold.it/2500x1666 4000w" class="img-responsive lazyload" />
    </div>

  </div>

  </div>

</div>

任何帮助都将被感激地接受

1 个答案:

答案 0 :(得分:0)

对于任何有兴趣的人,我通过在img周围添加一个包装并将padding-bottom设置为与图像匹配的比例来解决我的页面回流问题。在我的情况下,它是一个9x6图像,所以我做了以下等式

6/9 = 0.6666667 * 100 = 66.666667

我最终得到了66.5%的全宽幅图像和33.25%的50%宽度图像经过一些试验和错误,因为某些尺寸浏览器将图像解释为1px太高

http://codepen.io/elevenelevne/pen/jqYqJa

  <div class="lazy-wrapper ratio-padding">

    <img data-src="http://placehold.it/160x107" data-srcset="http://placehold.it/320x231 320w, http://placehold.it/640x426 640w, http://placehold.it/1000x666 1000w, http://placehold.it/2500x1666 2500w" sizes="100vw" class="lazyload" alt="" />

  </div>

  <div class="lazy-wrapper-2 ratio-padding-half">
    <img data-src="http://placehold.it/160x107" data-srcset="http://placehold.it/320x231 320w, http://placehold.it/640x426 640w, http://placehold.it/1000x666 1000w, http://placehold.it/2500x1666 2500w" sizes="(min-width: 768px) 50vw, 100vw" class="lazyload"
      alt="" />
  </div>

  <div class="lazy-wrapper-2 ratio-padding-half">
    <img data-src="http://placehold.it/160x107" data-srcset="http://placehold.it/320x231 320w, http://placehold.it/640x426 640w, http://placehold.it/1000x666 1000w, http://placehold.it/2500x1666 2500w" sizes="(min-width: 768px) 50vw, 100vw" class="lazyload"
      alt="" />
  </div>

CSS

.ratio-padding {
    padding-bottom: 66.5%; 
    height: 0;
}

.ratio-padding-half {
    padding-bottom: 33.25%; 
    height: 0;
}
.lazy-wrapper {
    position: relative;
    overflow:hidden;
    width: 100%;
    -webkit-transition: all 0.3s ease-in-out;
    -moz-transition: all 0.3s ease-in-out;
    -o-transition: all 0.3s ease-in-out;
    transition: all 0.3s ease-in-out;
    }

.lazy-wrapper-2 {
    width: 100%;
    float:left;
    }

@media (min-width: 768px) {
    .lazy-wrapper-2 {
    width: 50%;
    }
}

.lazy-wrapper img, .lazy-wrapper-2 img {
    max-width: 100%;
    width: 100%
}