2

I am developing a website and I have a problem with lazy loading images.

It was taking too much time to load the images so I checked the Browser Network Tab and I saw that Safari was loading multiple times the same image, slowing down the loading of the other media.

I reproduced the code to make as simple as possible and when I lazy load images the browser load them twice.

<style type="text/css">
[data-src]{
  opacity: 0;
  transition: all .4s ease;
}
[data-src].vis{
  opacity: 1;
}
</style>

<img data-src="https://via.placeholder.com/150/045b1f/ffff11" src="dot.png">
<img data-src="https://via.placeholder.com/150/045b44/ffff22" src="dot.png">
<img data-src="https://via.placeholder.com/150/045b77/ffff33" src="dot.png">
<img data-src="https://via.placeholder.com/150/045b00/ffff44" src="dot.png">

<script type="text/javascript">

  function lazy(){
    $('[data-src]').each(function(){
      var $img = $(this);
      var src = $img.attr('data-src');
      var img = new Image();
      img.src = src;
      $(img).on('load', function(){
        console.log('loaded',src);
        $img.attr('src',this.src);
        $img.addClass('vis');
      });
    });  
  }

  jQuery(function($){

    setTimeout(function(){
      lazy();
    },3000)

  });
</script>

I also made a CodePen https://codepen.io/nbl7/pen/GaoZXW

On my website this happen only on Safari and it loads the same image even 10 times. Probably because I call the lazy load function different times.

On the code I provided it happens also on Chrome.

Should the browser know already which image has been loaded and cache them without making new requests?

Thanks for the help.

nbl7
  • 511
  • 4
  • 14

1 Answers1

1

Here's a code that doesn't load the images twice:

function lazy() {
  $('[data-src]').each(function() {
    var img = this;
    var src = $(img).attr('data-src');
    $(img).attr('src', src);
    $(img).on('load', function() {
      console.log('loaded', src);
      $(img).addClass('vis');
    });
  });
}

jQuery(function($) {
  // lazy();
  setTimeout(function() {
    lazy();
  }, 3000)

});
[data-src] {
  opacity: 0;
  transition: all .4s ease;
}

[data-src].vis {
  opacity: 1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<img data-src="https://via.placeholder.com/150/045b1f/ffff11" src="">
<img data-src="https://via.placeholder.com/150/045b44/ffff22" src="">
<img data-src="https://via.placeholder.com/150/045b77/ffff33" src="">
<img data-src="https://via.placeholder.com/150/045b00/ffff44" src="">

You set the img src twice in your loop, and that means that it loads twice:

  • on this line: img.src = src; (line 6)

  • then on this line: $img.attr('src',this.src); (line 9)

muka.gergely
  • 8,063
  • 2
  • 17
  • 34