Created
August 14, 2020 04:52
-
-
Save kangdari/686f0a4fcea6ed72683dbf1caf80bfa8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8" /> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> | |
<title>InfiniteScroll</title> | |
<style> | |
* { | |
margin: 0; | |
padding: 0; | |
box-sizing: border-box; | |
list-style: none; | |
} | |
.title { | |
font-size: 24px; | |
font-weight: 600; | |
margin: 20px 0; | |
text-align: center; | |
} | |
.infinite_container { | |
width: 500px; | |
margin: 0 auto; | |
} | |
li.dog { | |
width: 300px; | |
height: 300px; | |
margin: 20px auto 0; | |
} | |
img { | |
width: 300px; | |
height: 300px; | |
object-fit: cover; | |
} | |
</style> | |
</head> | |
<body> | |
<h1 class="title">Obey the Dogs</h1> | |
<ul class="infinite_container"></ul> | |
<script> | |
const container = document.querySelector('.infinite_container'); | |
const getLastChild = () => document.querySelector('ul > li:last-child'); | |
// 이미지 로딩 문구 생성 | |
const loadingNewDogs = (newDogs) => { | |
const loadingTemplate = `<li><span>Loading New Dogs...</span></li>`; | |
return new Promise((resolve, reject) => { | |
// beforeend 가장 마지막 요소 뒤에 추가 | |
container.insertAdjacentHTML('beforeend', loadingTemplate); | |
setTimeout(() => { | |
resolve(newDogs); | |
// 로딩 제거 | |
container.removeChild(container.lastChild); | |
}, 1000); | |
}); | |
}; | |
// dog 요소 배열 생성 함수 | |
const createNewDogs = (count = 10) => { | |
const newDogArr = []; | |
const createNewDog = () => { | |
const li = document.createElement('li'); | |
li.className = 'dog'; | |
const img = document.createElement('img'); | |
li.append(img); | |
img.src = `https://source.unsplash.com/featured/?dogs?t=${Math.random()}`; | |
img.alt = 'dog'; | |
return li; | |
}; | |
for (let i = 0; i < count; i++) { | |
newDogArr.push(createNewDog()); | |
} | |
return newDogArr; | |
}; | |
const handleInfiniteScroll = (entries, observer) => { | |
const lastElem = [...entries].pop(); | |
if (lastElem.isIntersecting) { | |
loadingNewDogs(createNewDogs()).then((newDogs) => { | |
container.append(...newDogs); // 새로운 이미지 배열 추가 | |
currentLast = getLastChild(); | |
observer.unobserve(lastElem.target); // 기존의 마지막 요소 관찰 취소 | |
observer.observe(currentLast); // 새로우 마지막 요소 관찰 시작 | |
}); | |
} | |
}; | |
// 옵션 설정 | |
const options = { | |
root: null, | |
threshold: 0.5, | |
}; | |
// IntersectionObserver 객체 생성 | |
const io = new IntersectionObserver(handleInfiniteScroll, options); | |
container.append(...createNewDogs()); | |
io.observe(getLastChild()); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment