Intersection Observer
νκ² μμμ μμ μμ λλ μ΅μμ document
μ viewport
μ¬μ΄μ intersection λ΄μ λ³νλ₯Ό λΉλκΈ°μ μΌλ‘ κ΄μ°°νλ λ°©λ²μ
λλ€.
- νμ΄μ§κ° μ€ν¬λ‘€ λλ λμ€μ λ°μνλ μ΄λ―Έμ§λ λ€λ₯Έ 컨ν μΈ μ μ§μ° λ‘λ©
- μ€ν¬λ‘€ μμ, λ λ§μ 컨ν
μΈ κ° λ‘λ λ° λλλ§ λμ΄ μ¬μ©μκ° νμ΄μ§λ₯Ό μ΄λνμ§ μμλ λκ² νλ
infinite-scroll
ꡬν - μ¬μ©μμκ² κ²°κ³Όκ° νμλλ μ¬λΆμ λ°λΌ μμ μ΄λ μ λλ©μ΄μ μ μνν μ§ μ¬λΆλ₯Ό κ²°μ
μ ν΅μ μΈ μ€ν¬λ‘€ λ°©μ
κ³Όκ±°μλ intersection κ°μ§λ₯Ό ꡬννλ©΄ μν₯λ°λ μμλ₯Ό μκΈ° μν΄ Element.getBoundingClientRect() μ κ°μ λ©μλλ₯Ό νΈμΆ
μ΄ μ½λλ λ©μΈ μ€λ λμμ μ€νλκΈ° λλ¬Έμ λ€λ₯Έ μ½λμ μ½νκ² λλ©΄ μ±λ₯μ΄ λ§€μ° λ¨μ΄μ§ μ μμ΅λλ€
function setWindowScroll() {
document.addEventListener('scroll', () => {
boxs.forEach(box => {
if (isShowElement(box)) {
box.classList.add('show')
} else {
box.classList.remove('show')
}
console.count('Window Scroll')
})
})
function isShowElement(target) {
var rect = target.getBoundingClientRect()
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
rect.right <= (window.innerWidth || document.documentElement.clientWidth)
)
}
}
μΈν°μΉμ μ΅μ λ²
function setIntersectionObserver() {
const options = { }
const callback = (entries, observer) => {
entries.forEach(entry => {
const { isIntersecting, target } = entry
if (isIntersecting) {
target.classList.add('show')
} else {
target.classList.remove('show')
}
console.count('Intersection Observer')
})
}
const io = new IntersectionObserver(callback, options)
boxs.forEach(box => {
io.observe(box)
})
}
Performance
Parameter
const instance = new IntersectionObserver(callback [, options])
instance.observe(domElement)
Callback
- entries
- μΈν°μΉμ μ΅μ λ² μνΈλ¦¬λ₯Ό λ°°μ΄ννλ‘ λ°ν
- observer
- μΈν°μΉμ μ΅μ λ² μΈμ€ν΄μ€ κ°μ²΄
Options
μ΅μ λ²κ° μμλλ μμ μμ μ€μ νλ μ΅μ νμκ°μ μλλ€.
- root
- λμ κ°μ²΄μ κ°μμ±μ νμΈν λ μ¬μ©λλ λ·°ν¬νΈ μμμ λλ€
- rootMargin
- root κ° κ°μ§ μ¬λ°±μ λλ€. μ΄ μμ±μ κ°μ CSSμ margin μμ±κ³Ό μ μ¬ν©λλ€.
- threshold
- observerμ μ½λ°±μ΄ μ€νλ λμ μμμ κ°μμ± νΌμΌν°μ§λ₯Ό λνλ΄λ λ¨μΌ μ«μ νΉμ μ«μ λ°°μ΄μ λλ€
Method
observe
κ΄μ°° μμ
unobserve
κ΄μ°° μ’ λ£
disconnect
κ΄μ°° μΌμ μ€μ§
Polyfill
@@TODO
μ°Έκ³ μλ£
https://velog.io/@yejinh/Intersection-Observerλ‘-무ν-μ€ν¬λ‘€-ꡬννκΈ° https://developer.mozilla.org/ko/docs/Web/API/Intersection_Observer_API https://github.com/w3c/IntersectionObserver/tree/master/polyfill https://stackoverflow.com/questions/123999/how-to-tell-if-a-dom-element-is-visible-in-the-current-viewport/7557433#7557433 https://developers.google.com/web/fundamentals/performance/rendering/reduce-the-scope-and-complexity-of-style-calculations?hl=ko https://www.html5rocks.com/en/tutorials/speed/scrolling/#toc-reflowrepaint
β XMLHttpRequest Array β