Search code examples
javascriptjqueryimagelazy-loadingdimensions

How to fix image wrap size with the same size of Lazy Load image?


I'm looking for to show background-color image before lazy-loading with exactly the same dimension of the image. My script gest width and height of each images and applises on image-wrap.

Here is my code:

$(document).ready(function() {
  $('section .lazywrap').each(function() {

    var lazyWrap = $(this);
    var img = $(lazyWrap, this);

    lazyWrap.width(img.width());
    lazyWrap.height(img.height());

    console.log(lazyWrap.height());
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="/" class="lazy-wrap">
  <img class="lazy" width="472" src="img.jpg" data-original="img.jpg">
</a>

Web browser can get height value even if it's not implemented in <img>, BUT only for images who are visible in the viewport when the page is loading, because of lazy Load.

I read lot of things about responsive background image with the padding-bottom trick, but in my case I really need the real width and height value on this "background preview" and not a ratio. All my image have different height value.


Solution

  • Finally, I found an alternative solution with de lazy load plugin call lazysizes. It allows to use an background color with exactly the size instead of the image is being loading.