IntersectionObserver 를 사용해서 스크롤 이벤트의 부하 줄여주기
상황
해결
1. Intersection Observer 생성하기
2. 요소를 Observer에 등록하기
3. 우리의 상황에 맞게 코드를 수정하자
Last updated
Last updated
window.addEventListener('scroll', () => {
let stop;
let boundingRect;
let temp = 0;
for (let i = 0; i < stepElems.length; i++) {
step = stepElems[i];
boundingRect = step.getBoundingClientRect();
if (boundingRect.top > window.innerHeight * 0.1 &&
boundingRect.top < window.innerHeight * 0.8) {
inactivate(currentItem.dataset.action);
currentItem = graphicElems[step.dataset.index];
activate(currentItem.dataset.action);
}
}
});const io = new Intersectionobserver((entries, observer) => {
// 아래의 코드는 Intersection 이 될 때 마다 갱신된다.
ioIndex = +entries[0].target.dataset.index;
})for (let i = 0; i <stepElems.length; i++) {
io.observe(stepElems[i]);
} window.addEventListener('scroll', () => {
let stop;
let boundingRect;
for (let i = ioIndex - 1; i < ioIndex + 2; i++) {
step = stepElems[i];
if (!step) continue;
boundingRect = step.getBoundingClientRect();
if (boundingRect.top > window.innerHeight * 0.1 &&
boundingRect.top < window.innerHeight * 0.8) {
inactivate(currentItem.dataset.action);
currentItem = graphicElems[step.dataset.index];
activate(currentItem.dataset.action);
}
}
})