<img src='https://via.placeholder.com/500x400' data-src='https://dimg.donga.com/ugc/CDB/SHINDONGA/Article/5e/0d/9f/01/5e0d9f011a9ad2738de6.jpg'></img>
<br>
<img src='https://via.placeholder.com/500x400' data-src='https://img.animalplanet.co.kr/news/2020/07/06/700/da34f5o2h1n2je1uc579.jpg'></img>
<br>
<img src='https://via.placeholder.com/500x400' data-src="https://cdn.mkhealth.co.kr/news/photo/202004/img_MKH200424005_0.jpg"></img>
<br>
<img src='https://via.placeholder.com/500x400' data-src='https://www.sisa-news.com/data/photos/20200936/art_159912317533_32480a.jpg'></img>
body {
text-align: center
}
img {
width : 500px;
height: 400px;
margin: 40px;
display: inline-block;
}
// 옵션 객체
const options = {
// null을 설정하거나 무엇도 설정하지 않으면 브라우저 viewport가 기준이 된다.
root: null,
// 타겟 요소의 20%가 루트 요소와 겹치면 콜백을 실행한다.
threshold: 0.2
}
// Intersection Observer 인스턴스
const observer = new IntersectionObserver(function(entries,observer) {
entries.forEach(entry => {
// 루트 요소와 타겟 요소가 교차하면 dataset에 있는 이미지 url을 타겟요소의 src 에 넣어준다.
if (entry.isIntersecting) {
entry.target.src = entry.target.dataset.src
// 지연 로딩이 실행되면 unobserve 해준다.
observer.unobserve(entry.target)
}
})
}, options)
const imgs = document.querySelectorAll('img')
imgs.forEach((img) => {
// img들을 observe한다.
observer.observe(img)
})
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.