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.