<img src="https://images.unsplash.com/photo-1507525428034-b723cf961d3e?w=753&q=80" width="753" height="500">
<img src="https://images.unsplash.com/photo-1519046904884-53103b34b206?w=753&q=80" width="753" height="500">
<img data-src="https://images.unsplash.com/photo-1495954484750-af469f2f9be5?w=753&q=80" width="753" height="500" lazy>
<img data-src="https://images.unsplash.com/photo-1587502536900-baf0c55a3f74?w=753&q=80" width="753" height="500" lazy>
<img data-src="https://images.unsplash.com/photo-1510414842594-a61c69b5ae57?w=753&q=80" width="753" height="500" lazy>
<img data-src="https://images.unsplash.com/photo-1471922694854-ff1b63b20054?w=753&q=80" width="753" height="500" lazy>
<div data-src="https://images.unsplash.com/photo-1473186578172-c141e6798cf4?w=753&q=80" class="lazy-bg" lazy></div>
<div data-src="https://images.unsplash.com/photo-1487349384428-12b47aca925e?w=753&q=80" class="lazy-bg" lazy></div>
<div data-src="https://images.unsplash.com/photo-1527437934671-61474b530017?w=753&q=80" class="lazy-bg" lazy></div>
<div data-src="https://images.unsplash.com/photo-1473496169904-658ba7c44d8a?w=753&q=80" class="lazy-bg" lazy></div>
img {
display: block;
max-width: 100%;
margin: 10px auto;
border: 0;
}
.lazy-bg {
width: 753px;
height: 500px;
margin: 10px auto;
background-size: cover;
background-position: center;
}
// duyệt tất cả tấm ảnh cần lazy-load
var lazyImages = document.querySelectorAll('[lazy]');
// khi tấm ảnh gần chạm viewport (còn 100px nữa là chạm), thì load tấm ảnh ngay
var threshold = 100;
// tránh vấn đề về performance
var timeout;
function lazyload () {
clearTimeout(timeout);
timeout = setTimeout(function() {
var scrollTop = window.pageYOffset;
lazyImages.forEach(function(lazyImage) {
var src = lazyImage.dataset.src;
// khi vị trí tấm ảnh gần chạm viewport, load ngay
if (lazyImage.offsetTop < (window.innerHeight + scrollTop + threshold)) {
lazyImage.tagName.toLowerCase() === 'img'
// <img>: copy data-src sang src
? lazyImage.src = src
// <div>: copy data-src sang background-image
: lazyImage.style.backgroundImage = "url(\'" + src + "\')";
// copy xong rồi thì bỏ attribute lazy đi
lazyImage.removeAttribute('lazy');
}
});
// tất cả tấm ảnh đã được load xong, dọn dẹp và đi thôi.
if (lazyImages.length == 0) {
document.removeEventListener('scroll', lazyload);
}
}, 10);
}
document.addEventListener('scroll', lazyload);
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.