이미지 동영상 Lazy Load

페이지 정보

그누보드자료실

본문

<style>  
.gant-mp4 {  
	display:block;  
	max-width:100%;  
	margin:10px 0;  
}  
  
.gant-mp4 video {  
	max-width:100%;  
	display:block;  
	background:#000;  
}  
</style>  
  
<div class="container">  
    <h2>스크롤하면 이미지/동영상 로드</h2>  
  
    <!-- 이미지 Lazy Load -->  
    <img data-src="01.jpg" alt="Lazy Image">  
    <br><img data-src="02.jpg" alt="Lazy Image">  
  
    <!-- 동영상 Lazy Load -->  
    <div class='gant-mp4'>  
        <video data-src="01.mp4" type='video/mp4' autoplay loop controls muted></video>  
    </div>  
    <div class='gant-mp4'>  
        <video data-src="02.mp4" type='video/mp4' autoplay loop controls muted></video>  
    </div>  
    <div class='gant-mp4'>  
        <video data-src="03.mp4" type='video/mp4' autoplay loop controls muted></video>  
    </div>  
    <div class='gant-mp4'>  
        <video data-src="04.mp4" type='video/mp4' autoplay loop controls muted></video>  
    </div>  
    <div class='gant-mp4'>  
        <video data-src="05.mp4" type='video/mp4' autoplay loop controls muted></video>  
    </div>  
</div>  
  
<script>  
document.addEventListener("DOMContentLoaded", function () {  
    const elements = document.querySelectorAll("img[data-src], video[data-src]");  
  
    elements.forEach((el, index) => {  
        if (index === 0) { // 첫 번째 요소(이미지 & 비디오)만 즉시 로드  
            el.src = el.getAttribute("data-src");  
            el.removeAttribute("data-src");  
            el.setAttribute("data-loaded", "true");  
            el.style.opacity = "1"; // 즉시 표시  
        } else {  
            el.style.opacity = "0"; // 초기 투명 상태  
            el.style.transition = "opacity 0.5s ease-in-out"; // 부드러운 페이드 인  
        }  
    });  
  
    const observer = new IntersectionObserver((entries) => {  
        entries.forEach(entry => {  
            const el = entry.target;  
  
            if (entry.isIntersecting) {  
                if (!el.hasAttribute("data-loaded")) {  
                    el.src = el.getAttribute("data-src");  
                    el.removeAttribute("data-src");  
                    el.setAttribute("data-loaded", "true");  
  
                    setTimeout(() => {  
                        el.style.opacity = "1";  
                    }, 100);  
                }  
  
                // 비디오의 경우 재생/일시정지 처리  
                if (el.tagName === "VIDEO") {  
                    el.play();  
                }  
            } else {  
                if (el.tagName === "VIDEO") {  
                    el.pause();  
                }  
            }  
        });  
    }, { threshold: 0.5 });  
  
    elements.forEach(el => observer.observe(el));  
});  
</script>

댓글 0
그누보드
전체 30 / 1 페이지
홈으로 전체메뉴 마이메뉴
전체 검색