<style>
* {
padding: 0;
margin: 0;
background-color: rgb(255, 237, 213);
}
.progress-bar {
width: 100%;
height: 5px;
box-sizing: border-box;
}
.progress-bar-meter {
background-color: red;
width: 0%;
height: inherit;
transition: width .5s;
}
.lazy-images {
width: 24%;
}
.images {
text-align: center;
}
</style>
<div class="progress-bar">
<div class="progress-bar-meter"></div>
</div>
<div class="images">
<img src="https://cdn.pixabay.com/photo/2020/07/10/22/38/cows-5392356_1280.jpg" class="lazy-images" alt="me" />
<img src="https://cdn.pixabay.com/photo/2020/07/02/08/00/landscape-5362157_1280.jpg" class="lazy-images" alt="me" />
<img src="https://cdn.pixabay.com/photo/2020/07/08/05/31/gray-cat-5382617_1280.jpg" class="lazy-images" alt="me" />
<img src="https://cdn.pixabay.com/photo/2020/07/02/17/29/landscape-5363681_1280.jpg" class="lazy-images" alt="me" />
</div>
<script>
function LazyLoader({ queryImages, queryProgress }) {
let progressLoad = 0;
const lazyImages = document.querySelectorAll(queryImages)
const progressBarMeter = document.querySelector(queryProgress)
const updateProgressBar = () => progressBarMeter.style.width = `${100 / (lazyImages.length / ++progressLoad) || 0}%`
lazyImages.forEach(
lazyImage =>
// lazyImage.naturalWidth > 0 - т.е. уже в кэше
lazyImage.naturalWidth > 0
?
updateProgressBar()
:
new Promise((resolve, reject) => lazyImage.onload = () => resolve(updateProgressBar()))
)
}
document.addEventListener('DOMContentLoaded', function () {
new LazyLoader({
queryImages: 'img.lazy-images',
queryProgress: '.progress-bar-meter'
})
});
</script>