ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

JS

Infinite Scroll

choi95 2021. 7. 1. 14:23

Question

1. ์ตœ์ดˆ์—๋Š” 20๊ฐœ์˜ ๋ชฉ๋ก์„ ๋ถˆ๋Ÿฌ์˜จ๋‹ค.

2. ์Šคํฌ๋กค์„ ์ตœํ•˜๋‹จ์œผ๋กœ ์ด๋™์‹œ 'loading' ์ƒํƒœ ํ‘œ์‹œ๊ฐ€ ๋‚˜ํƒ€๋‚˜๋ฉฐ, ์ดํ›„์˜ 20๊ฐœ ๋ชฉ๋ก์„ ๋” ๊ฐ€์ ธ์˜จ๋‹ค.

3. ๋กœ๋”ฉ ์™„๋ฃŒ์‹œ 'loading'ํ‘œ์‹œ๊ฐ€ ์‚ฌ๋ผ์ง€๋ฉฐ, ๊ฐ€์ ธ์˜จ ๋ชฉ๋ก์ด ํ•˜๋‹จ์— ์ถ”๊ฐ€๋œ๋‹ค. (๋ฌดํ•œ ๋ฐ˜๋ณต)

 

Solution

const loadMore = async () => {
  const target = page ? fetchMoreTrigger : app;
  target.classList.add("loading");
  await renderList(page++);
  target.classList.remove("loading");
};

const onScroll = async e => {
  const {scrollTop, scrollHeight, clientHeight} = e.target.scrollingElement;
  if(scrollHeight - scrollTop === clientHeight) {
    const target = page ? fetchMoreTrigger : app;
    target.classList.add("loading");
    await renderList(page++);
    target.classList.remove("loading");
  }
};

 

Issue

1. ์Šคํฌ๋กค ์ด๋ฒคํŠธ๋ฅผ ํ•˜๋ฉด ์ด๋ฒคํŠธ ํƒ€๊ฒŸ์— scrollingElement ํ”„๋กœํผํ‹ฐ๊ฐ€ ์žˆ๋Š”๋ฐ ์ด๊ฒƒ์„ ํ†ตํ•ด ํ˜„์žฌ ์Šคํฌ๋กค ์ƒํƒœ์™€ ๊ด€๋ จ๋œ    ์ •๋ณด๋ฅผ ์–ป์„ ์ˆ˜ ์žˆ๋‹ค.    ํ•ด๋‹น scrollingElement ๋‚ด์— ๋‹ค์Œ๊ณผ ๊ฐ™์€ 3๊ฐ€์ง€ ํ”„๋กœํผํ‹ฐ๋“ค์„ ๋””์ŠคํŠธ๋Ÿญ์ณ๋ง ํ• ๋‹นํ•œ๋‹ค.

  • clientHeight: ์›น ๋ธŒ๋ผ์šฐ์ € ์ฐฝ(๋‚ด์šฉ์ด ๋ณด์—ฌ์ง€๋Š” ์˜์—ญ)์˜ ๋†’์ด
  • scrollTop: ํ˜„์žฌ ์Šคํฌ๋กค๋œ ๋ถ€๋ถ„์˜ ๋งจ ์œ„์˜ ๋†’์ด(=ํ˜„์žฌ ์Šคํฌ๋กค์˜ ์œ„์น˜)
  • scrollHeight: ๋ฌธ์„œ์˜ ์ด ๋†’์ด(=์Šคํฌ๋กค ๋Œ€์ƒ์˜ ์ด ๋†’์ด)

2. '(์ „์ฒด ์Šคํฌ๋กค ์˜์—ญ) - (ํ˜„์žฌ ์Šคํฌ๋กค์˜ ์œ„์น˜)'์˜ ๊ฐ’์ด (ํ˜„์žฌ ์Šคํฌ๋กค ๋œ ์ƒํƒœ์—์„œ์˜ ๋ณด์—ฌ์ง€๋Š” ์˜์—ญ)๊ณผ ๊ฐ™๋‹ค๋ฉด ๋” ์ด์ƒ ์Šคํฌ๋กค์„

    ํ•  ๊ณต๊ฐ„์ด ์—†๋‹ค๋Š” ์˜๋ฏธ์ด๋ฉฐ ์ด ์‹์„ ์กฐ๊ฑด๋ฌธ ๋‚ด์— ์‚ฌ์šฉํ•œ๋‹ค.

 

3. ์ดˆ๊ธฐ ์ƒํƒœ์™€ ์ดํ›„ ์—…๋ฐ์ดํŠธ ๋  ๋•Œ์˜ ํŽ˜์ด์ง€๋Š” ๋ณ„๋„๋กœ ๊ตฌ์„ฑํ•ด์•ผ ํ•˜๊ธฐ ๋•Œ๋ฌธ์— ์‚ผํ•ญ์—ฐ์‚ฐ์ž๋ฅผ ํ†ตํ•ด ์กฐ๊ฑด์— ๋งž๊ฒŒ taget ๋ณ€์ˆ˜๋ฅผ 

    ๊ฐ๊ธฐ ๋‹ค๋ฅด๊ฒŒ ํ• ๋‹นํ•ด ์ค€๋‹ค. (์ดˆ๊ธฐ page ๋ณ€์ˆ˜ ๊ฐ’์€ 0์ด๊ธฐ ๋•Œ๋ฌธ์— false)

 

Refactoring

const loadMore = async () => {
  const target = page ? fetchMoreTrigger : app;
  target.classList.add("loading");
  await renderList(page++);
  target.classList.remove("loading");
};

const onScroll = e => {
  const {scrollTop, scrollHeight, clientHeight} = e.target.scrollingElement;
  if(scrollHeight - scrollTop === clientHeight) {
    loadMore();
  }
};
๋Œ“๊ธ€
๊ณต์ง€์‚ฌํ•ญ
์ตœ๊ทผ์— ์˜ฌ๋ผ์˜จ ๊ธ€
์ตœ๊ทผ์— ๋‹ฌ๋ฆฐ ๋Œ“๊ธ€
Total
Today
Yesterday
๋งํฌ
TAG
more
ยซ   2024/12   ยป
์ผ ์›” ํ™” ์ˆ˜ ๋ชฉ ๊ธˆ ํ† 
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31
๊ธ€ ๋ณด๊ด€ํ•จ