Skip to content

Instantly share code, notes, and snippets.

@kangdari
Last active August 14, 2020 04:21
Show Gist options
  • Save kangdari/87e3482ce1d0189057e40f7901fe9512 to your computer and use it in GitHub Desktop.
Save kangdari/87e3482ce1d0189057e40f7901fe9512 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>LazyLoading</title>
<style>
* {
margin: 0;
padding: 0;
}
body {
display: flex;
flex-direction: column;
align-items: center;
}
.image {
display: block;
width: 300px;
height: 300px;
margin: 10px;
color: #fff;
}
</style>
</head>
<body>
<div class="image" data-src="https://source.unsplash.com/random/200x200?t=2">No Image</div>
<div class="image" data-src="https://source.unsplash.com/random/200x200?t=2">No Image</div>
<div class="image" data-src="https://source.unsplash.com/random/200x200?t=3">No Image</div>
<div class="image" data-src="https://source.unsplash.com/random/200x200?t=4">No Image</div>
<div class="image" data-src="https://source.unsplash.com/random/200x200?t=5">No Image</div>
<div class="image" data-src="https://source.unsplash.com/random/200x200?t=6">No Image</div>
<div class="image" data-src="https://source.unsplash.com/random/200x200?t=7">No Image</div>
<div class="image" data-src="https://source.unsplash.com/random/200x200?t=9">No Image</div>
<div class="image" data-src="https://source.unsplash.com/random/200x200?t=9">No Image</div>
<div class="image" data-src="https://source.unsplash.com/random/200x200?t=10">No Image</div>
</body>
<script>
const lazyLoadImage = (entries, observer) => {
entries.forEach((entry) => {
// 관찰 요소가 viewport 안에 들어왔을 경우 이미지 로드
if (entry.isIntersecting) {
const { target } = entry;
target.style.backgroundImage = `url("${target.dataset.src}")`;
target.style.backgroundSize = 'cover';
target.textContent = '';
// 관찰 중지
observer.unobserve(target);
}
});
};
const options = {
root: null,
threshold: 1,
};
const io = new IntersectionObserver(lazyLoadImage, options);
// 관찰할 대상을 선언하고 해당 속성을 관찰
const images = document.querySelectorAll('.image');
images.forEach((image) => io.observe(image));
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment