I made a solution with several benefits:
- works with cache
- all images full responsive
- load just one image
I generate all tags but wrap them in HTML comment. Browser don't load images.
<div class="stage-image has-content">
<div class="stage-image-item">
<!-- <img src="/storage/hochschule/upload/150902-4654.jpg" srcset="/storage/_processed_/3/e/csm_150902-4654_8eaf6a0880.jpg 764w,/storage/_processed_/3/e/csm_150902-4654_d0f788b245.jpg 1084w,/storage/hochschule/upload/150902-4654.jpg 1170w," sizes="(max-width: 767px) 764px, (min-width: 768px) and (max-width: 991px) 1084px, (min-width: 992px) 1170px" alt="" > -->
</div>
<div class="stage-image-item">
<!-- <img src="/storage/hochschule/upload/151022-0041.jpg" srcset="/storage/_processed_/f/e/csm_151022-0041_d0b564fdb1.jpg 764w,/storage/_processed_/f/e/csm_151022-0041_b993bf6066.jpg 1084w,/storage/hochschule/upload/151022-0041.jpg 1170w," sizes="(max-width: 767px) 764px, (min-width: 768px) and (max-width: 991px) 1084px, (min-width: 992px) 1170px" alt="" > -->
</div>
<div class="stage-image-item">
<!-- <img src="/storage/hochschule/upload/151013-7145.jpg" srcset="/storage/_processed_/e/6/csm_151013-7145_42e2692215.jpg 764w,/storage/_processed_/e/6/csm_151013-7145_3ee771dee1.jpg 1084w,/storage/hochschule/upload/151013-7145.jpg 1170w," sizes="(max-width: 767px) 764px, (min-width: 768px) and (max-width: 991px) 1084px, (min-width: 992px) 1170px" alt="" > -->
</div>
<div class="stage-image-item">
<!-- <img src="/storage/hochschule/upload/151104-1433.jpg" srcset="/storage/_processed_/f/b/csm_151104-1433_7bf357e27a.jpg 764w,/storage/_processed_/f/b/csm_151104-1433_b7c9f24147.jpg 1084w,/storage/hochschule/upload/151104-1433.jpg 1170w," sizes="(max-width: 767px) 764px, (min-width: 768px) and (max-width: 991px) 1084px, (min-width: 992px) 1170px" alt="" > -->
</div>
<div class="stage-image-item">
<!-- <img src="/storage/hochschule/upload/150930-6077.jpg" srcset="/storage/_processed_/a/e/csm_150930-6077_d7a31d91e3.jpg 764w,/storage/_processed_/a/e/csm_150930-6077_87603957bf.jpg 1084w,/storage/hochschule/upload/150930-6077.jpg 1170w," sizes="(max-width: 767px) 764px, (min-width: 768px) and (max-width: 991px) 1084px, (min-width: 992px) 1170px" alt="" > -->
</div>
</div>
Then remove randomly HTML comment from one and browser loads them.
(function ($) {
$.fn.rand = function () {
return this.eq(Math.floor(Math.random() * this.length));
};
})(jQuery);
// Get random image
var stageImageDiv = $(this).find('.stage-image');
$(stageImageDiv).children().rand().replaceWith(function () {
var string = $(this).html();
return string.replace(/<!--/g, '').replace(/-->/g, '');
});