Angular 무한 스크롤 적용하기

알고리즘 pseudo code

  1. 페이지 로딩 시점에 get(9)

  2. 스크롤바가 하단에 가까우면 받아오고, 받아오기 인덱스 true if(height<200px) get(9) getIndex=true

  3. 받아오는 동안에는 요청 안하기 if(getIndex==true) return 0

  4. 받아온 값이 없을 경우에는 return 0하고 searchEndIndex를 true로 하기 if(res.length==0) return 0 searchEndIndex=true

HostListener Decorator Component 작성

아래와 같이 호스트의 이벤트를 감지한다.

import { HostListener, Inject} from "@angular/core";
import { DOCUMENT } from "@angular/common";

export class LayoutNavComponent implements OnInit {
  constructor(@Inject(DOCUMENT) private document: Document) { }
}
@HostListener("window:scroll", ['$event.target'])
onWindowScroll() {
  //we'll do some stuff here when the window is scrolled
  console.log(this.document.body.scrollHeight);
  console.log("scrollTop:",this.document.documentElement.scrollTop);
  let scrollHeight=this.document.documentElement.scrollHeight;
  let readHeight=this.document.documentElement.scrollTop+this.document.documentElement.clientHeight;

  if((-10<=(readHeight-scrollHeight))&&((readHeight-scrollHeight)<=10)){
   this.groupService.getGroupsBySearchKey(this.locationService.locationDepth1, this.locationService.locationDepth2, this.groupService.searchKey);
  }
}

scroll event의 성능향상을 위한 Tip

모든 이벤트 마다 onScroll 함수를 발생시키면 CPU의 성능을 많이 차지하므로 다음과 같이 함수에 delay를 주어 이를 해결할 수 있다.

function () {
    if (waiting) {
        return;
    }
    waiting = true;

    scroll();

    setTimeout(function () {
        waiting = false;
    }, 100);
}

하드웨어 가속시키기

하드웨어 가속이란 그래픽 처리 장치를 이용하여 중앙처리 장치의 처리량을 줄이고, 브라우저의 렌더링을 효율화하는 것을 말한다. css 작업에 하드웨어 가속을 활성화하면, 작업처리가 빨라져서 웹페이지의 렌더링을 보다 빠르게 할 수 있다.

특정 엘레멘트에 어떤 지시를 내리면 엘리먼트는 자신의 레이어에 분류되고 페이지에 있는 다른 엘리멘트와 독립되어 렌더링 된다. 결론만 말하면 css에 다음과 같은 속성을 붙이면 하드웨어를 가속화 하여 빨리 렌더링이 가능하다.

transform: 3dtransforms(0,0,0)

위 명령어는 3d가 아닌 엘레먼트에 가짜로 3d속성을 주므로써 해당 element의 렌더링을 cpu가 아닌 gpu가 담당하게 하여 렌더링 속도를 높이며, will-change 명령어는 엘레먼트에 어떤 변경을 할 것인지 브라우저에게 미리 알려주므로써 최적화 하는 것이다. 페이지는 순식간에 갱신돼 부드러운 화면처리가 가능하게 된다.

참조