无限滚动加载解决方案之虚拟滚动(下)

c6ba68f555ff0515ef5ac6a7e2f6b92d.gif

上一篇文章(点击跳转)我们用短短几十行代码就实现了一个相对性能较强的无限滚动加载逻辑,通过每个元素脱离文档流,然后使用布局高度来顶到固定的位置从而实现虚拟滚动的效果。但是应用场景仅仅局限于固定高度的元素,即滚动列表中的每个子元素高度是固定且一致,可业务场景不单单只有等高这种情况,极有可能还存在的元素高度不确定且各个子元素高度不一致的情况,今天将带来滚动列表中子元素不等高的情况下对应的技术方案。

滚动方式介绍

原理:用固定个数的元素来模拟无线滚动加载,通过位置的布局来达到滚动后的效果

由于无限滚动的列表元素高度是和产品设计的场景有关,有定高的,也有不定高的。

定高:滚动列表中子元素高度相等。

不定高:滚动列表中子元素高度都随机且不相等。

  不定高方案

由于开发中遇到的不一定是等高的元素,例如刚开始所看到的内容,有好几类内容交互卡片,纯文字的,文字加视频的,文字加一张图的,文字加多张图的,纯图片的,纯文字的等等。元素卡片高度都是不相等的。高度不定,而且返回的内容是不固定的,所以每次返回的内容的可能组成非常多的方式,这样上面的方案就不适用了。

13a43055cbaec4dc5304aaae620d7cd5.png

  • 实现原理

通过观察者方式,来观察元素是否进入视口。我们会对固定元素的第一个和最后一个分别打上标签,例如把第一个元素的id设置为top,把最后一个元素的id值设置为bottom。

此时调用异步的api:IntersectionObserver,他能获取到进入到视口的元素,判断当前进入视口的元素是最后个元素,则说明内容是往上滚的,如果进入视口的是第一个元素,则说明内容是往下滚的。

我们依次保存下当前第一个元素距离顶部的高度和距离底部的高度,赋值给滚动内容元素的paddingTop和paddingBottom,这样内容区域的高度就不会坍塌,依旧保持这传统滚动元素充满列表时的内容高度:

bf97a70d115ebb26de4233923b7fbdcb.png

  • 滚动效果

9c41fa135e7ccf33dda3196ed5e1d539.gif

  • 实现方式

我们首先定义交叉观察者:IntersectionObserver。

IntersectionObserver API是异步的,不随着目标元素的滚动同步触发,性能消耗极低。

获取到指定元素,然后在元素上添加观察事件。

const box = document.querySelector('xxxx');
const intersectionObserver = new IntersectionObserver((entries) => {
  entries.forEach((entry) => {
    if (entry.isIntersecting) {
       // 进入可视区域
      ....
    }
  })
}, {
  threshold: [0, 0.5],
  root: document.querySelector('.wrap'),
  rootMargin: "10px 10px 30px 20px",
});
intersectionObserver.observe(box);
‍ ‍ ‍

确定元素的顺序和位置,在元素的第一个值和最后一个值上挂上ref,方便获取指定的dom元素,这里我们一共使用20个元素来实现无线滚动加载

const NODENUM = 20;
...
const $bottomElement = useRef();
const $topElement = useRef();
const $downAnchor:any = useRef();
const $upAnchor:any = useRef();
...


const getReference = (index) => {
  switch (index) {
    case 0:
      return $topElement;
    case 5:
      return $upAnchor;
    case 10:
      return $downAnchor;
    case (NODENUM - 1):
      return $bottomElement;
    default:
      return null;
  }
}

定义起始元素和截止元素,在第一个元素和最后一个元素上绑定id值:top && bottom。通过调用getReference方法获取ref变量绑定在元素上。

<div className="container">
  <div ref={$wrap} style={{ paddingTop: `${paddingTop}px`, paddingBottom: `${paddingBottom}px`, 'position': 'relative' }}>
        {currentArr.slice(start, end).map((item, index) => {
          const refVal = getReference(index);
          const id = index === 0 ? 'top' : (index === (NODENUM - 1) ? 'bottom' : '');
          const classValue = index % 4 === 0 ? 'test' : ''
          return  <div id={id} ref={refVal} key={item}>
              <div className={`item ${classValue}`}>
                {item}
              </div>
            </div>
        })}
      </div>
    </div>

获取到指定元素,然后在元素上添加观察事件,由于IntersectionObserver接收一个回调函数,传入回调函数的参数为该元素的一些相关属性值,我们通过对元素的id进行判断来区分当前是向上滚动还是向下滚动,同时改变起始值start和结束值end去切分数据数组,通过数据去驱动视图重新渲染。

entry中包含的isIntersecting表示是否进入可视区域。

entry.target.id则为进入可视区域的元素的id,我们在第0个元素上绑定id为top,在最后一个元素上绑定id为bottom

const callback = (entries, observer) => {
    entries.forEach((entry, index) => {
      const listLength = currentArr.length;
      // 向下滚动
      if (entry.isIntersecting && entry.target.id === "bottom") {
        const maxStartIndex = listLength - 1 - NODENUM;
        const maxEndIndex = listLength - 1;
        const newStart = (end - 10) <= maxStartIndex ? end - 10 : maxStartIndex;
        const newEnd = (end + 10) <= maxEndIndex ? end + 10 : maxEndIndex;
        // 加载更多数据,这里模拟了每次拉新数据40条
        if (newEnd + 10 >= maxEndIndex && !config.current.isRequesting && true) {
          currentArr.push(...arr.slice(i * 40, (i + 1)* 40))
          i++;
        }
        if (end + 10 > maxEndIndex) return;
        updateState(newStart, newEnd, true);
      }
      // 向上滚动
      if (entry.isIntersecting && entry.target.id === "top") {
        const newEnd = end === NODENUM ? NODENUM : (end - 10 > NODENUM ? end - 10 : NODENUM);
        const newStart = start === 0 ? 0 : (start - 10 > 0 ? start - 10 : 0);
        updateState(newStart, newEnd, false);
      }
    });
  }

封装一个paddingTop和paddingBottom更新的函数,如果有当前的padding值,则取出渲染,如果没有,则保存下当前的paddingTop和paddingBottom。

const updateState = (newStart, newEnd, isDown) => {
  if (config.current.setting) return;
  config.current.syncStart = newStart;
  if (start !== newStart || end !== newEnd) {
    config.current.setting = true;
    setStart(newStart);
    setEnd(newEnd);
    const page = ~~(newStart / 10) - 1;
    if (isDown) {  //向下
      newStart !== 0 && !config.current.paddingTopArr[page] && (config.current.paddingTopArr[page] = $downAnchor.current.offsetTop);
      // setPaddingTop(check ? config.current.paddingTopArr[page] : $downAnchor.current.offsetTop);
      setPaddingTop(config.current.paddingTopArr[page]);
      setPaddingBottom(config.current.paddingBottomArr[page] || 0);
    }else {  //向上
      // const newPaddingBottom = $wrap.current.scrollHeight - $upAnchor.current.offsetTop;
      const newPaddingBottom = $wrap.current.scrollHeight - $downAnchor.current.offsetTop;
      newStart !== 0 && (config.current.paddingBottomArr[page] = newPaddingBottom);
      setPaddingTop(config.current.paddingTopArr[page] || 0);
      // setPaddingBottom(check ? config.current.paddingBottomArr[page] : newPaddingBottom);
      setPaddingBottom(config.current.paddingBottomArr[page]);
    }
    setTimeout(() => {config.current.setting = false;},0);
  }
}
  • 白屏问题

在开发过程中发现,数据量非常大的情况下,快速滚动页面,由于api是异步的,导致更新方法触发没跟上,所以需要对滚动事件再做一层的观察,判断是否当前的滚动高度已经更新过了,没更新则通过滚动结束后强行更新,当然,一定要记得对这个滚动事件加一层节流,减少事件触发频率。

  • 兼容问题

4774675cbe8823844a80ee17cbd14ecc.png

在safari的兼容问题,可以使用polyfill来解决。

  • 整体代码

// index.less
.item {
  width: 100vw;
  height: 240rpx;
  border-bottom: 2rpx solid black;
}


.test {
  height: 110rpx;
}


.container {
  width: 100vw;
  height: 100vh;
  overflow: scroll;
  -webkit-overflow-scrolling: touch;
}
// index.tsx
import { createElement, useEffect, useRef, useState } from "rax";
import "./index.less";
const arr = [];
// 模拟一共有2万条数据
for (let i = 0; i < 20000; i++) {
  arr.push(i);
}
let i = 1;
// 默认第一屏取2页数据
const currentArr = arr.slice(0, 40), screenH = window.screen.height;
const NODENUM = 20;


function throttle(fn, wait) {
  var timeout;
  return function() {
    var ctx = this, args = arguments;
    clearTimeout(timeout);
    timeout = setTimeout(function() {
      fn.apply(ctx, args);
    }, wait);
  };
}




function Index(props) {
  const [start, setStart] = useState(0);
  const [end, setEnd] = useState(NODENUM);
  const [paddingTop, setPaddingTop] = useState(0);
  const [paddingBottom, setPaddingBottom] = useState(0);
  const [observer, setObserver] = useState(null);
  const $bottomElement = useRef();
  const $topElement = useRef();
  const $downAnchor:any = useRef();  //定位paddingTop的距离
  const $upAnchor:any = useRef(); //定位paddingBottom的距离
  const $wrap:any = useRef(); //协助定位paddingBottom的距离
  const container = useRef();
  const config = useRef({
    isRequesting: false,
    paddingTopArr: [],  //paddingTop数据栈
    paddingBottomArr: [], //paddingBottom数据栈
    preScrollTop: 0,
    syncStart: 0,
    setting: false,
  });


  const getReference = (index) => {
    switch (index) {
      case 0:
        return $topElement;
      case 5:
        return $upAnchor;
      case 10:
        return $downAnchor;
      case (NODENUM - 1):
        return $bottomElement;
      default:
        return null;
    }
  }




  const resetObservation = () => {
    observer && observer.unobserve($bottomElement.current);
    observer && observer.unobserve($topElement.current);
  }


  const intiateScrollObserver = () => {
    const options = {
      root: null,
      rootMargin: '0px',
      threshold: 0.1
    };
    const Observer = new IntersectionObserver(callback, options);
    if ($topElement.current) {
      Observer.observe($topElement.current);
    }
    if ($bottomElement.current) {
      Observer.observe($bottomElement.current);
    }
    setObserver(Observer);
  }


  const callback = (entries, observer) => {
    entries.forEach((entry, index) => {
      const listLength = currentArr.length;
      // 向下滚动
      if (entry.isIntersecting && entry.target.id === "bottom") {
        const maxStartIndex = listLength - 1 - NODENUM;
        const maxEndIndex = listLength - 1;
        const newStart = (end - 10) <= maxStartIndex ? end - 10 : maxStartIndex;
        const newEnd = (end + 10) <= maxEndIndex ? end + 10 : maxEndIndex;
        if (newEnd + 10 >= maxEndIndex && !config.current.isRequesting && true) {
          currentArr.push(...arr.slice(i * 40, (i + 1)* 40))
          i++;
        }
        if (end + 10 > maxEndIndex) return;
        updateState(newStart, newEnd, true);
      }
      // 向上滚动
      if (entry.isIntersecting && entry.target.id === "top") {
        const newEnd = end === NODENUM ? NODENUM : (end - 10 > NODENUM ? end - 10 : NODENUM);
        const newStart = start === 0 ? 0 : (start - 10 > 0 ? start - 10 : 0);
        updateState(newStart, newEnd, false);
      }
    });
  }


const updateState = (newStart, newEnd, isDown) => {
  if (config.current.setting) return;
  config.current.syncStart = newStart;
  if (start !== newStart || end !== newEnd) {
    config.current.setting = true;
    setStart(newStart);
    setEnd(newEnd);
    const page = ~~(newStart / 10) - 1;
    if (isDown) {  //向下
      newStart !== 0 && !config.current.paddingTopArr[page] && (config.current.paddingTopArr[page] = $downAnchor.current.offsetTop);
      // setPaddingTop(check ? config.current.paddingTopArr[page] : $downAnchor.current.offsetTop);
      setPaddingTop(config.current.paddingTopArr[page]);
      setPaddingBottom(config.current.paddingBottomArr[page] || 0);
    }else {  //向上
      // const newPaddingBottom = $wrap.current.scrollHeight - $upAnchor.current.offsetTop;
      const newPaddingBottom = $wrap.current.scrollHeight - $downAnchor.current.offsetTop;
      newStart !== 0 && (config.current.paddingBottomArr[page] = newPaddingBottom);
      setPaddingTop(config.current.paddingTopArr[page] || 0);
      // setPaddingBottom(check ? config.current.paddingBottomArr[page] : newPaddingBottom);
      setPaddingBottom(config.current.paddingBottomArr[page]);
    }
    setTimeout(() => {config.current.setting = false;},0);
  }
}


useEffect(() => {
  document.getElementsByClassName('container')[0].addEventListener('scroll', scrollEventListner);
}, [])


  useEffect(() =>  {
    resetObservation();
    intiateScrollObserver();
  }, [end, currentArr])


  const scrollEventListner = throttle(function (event) {
    const scrollTop = document.getElementsByClassName('container')[0].scrollTop;
    let index = config.current.paddingTopArr.findIndex(e => e > scrollTop);
    index = index <= 0 ? 0 : index;
    const len = config.current.paddingTopArr.length;
    len && (config.current.paddingTopArr[len - 1] < scrollTop) && (index = len);
    const newStart = index * 10;
    const newEnd = index * 10 + NODENUM;
    if (newStart === config.current.syncStart) {
      config.current.preScrollTop = scrollTop;
      return;
    }
    updateState(newStart, newEnd, scrollTop > config.current.preScrollTop);  //true为往下滚动  false为往上滚动
    config.current.preScrollTop = scrollTop;
  }, 100);


  return (
    <div className="container">
      <div ref={$wrap} style={{ paddingTop: `${paddingTop}px`, paddingBottom: `${paddingBottom}px`, 'position': 'relative' }}>
        {currentArr.slice(start, end).map((item, index) => {
          const refVal = getReference(index);
          const id = index === 0 ? 'top' : (index === (NODENUM - 1) ? 'bottom' : '');
          const classValue = index % 4 === 0 ? 'test' : ''
          return  <div id={id} ref={refVal} key={item}>
              <div className={`item ${classValue}`}>
                {item}
              </div>
            </div>
        })}
      </div>
    </div>
  );
}


export default Index;

总结

定高和不定高2类虚拟滚动,适合用户消费海量数据的场景,尤其是社交媒体这类数据消费。而像通讯录,好友列表这类数据量单一且不会特别多的情况,还是用传统的滚动体验会更好。技术选型就按照自己业务的实际需要去出发选择,千万不要强行套用。

关于懒加载这块的问题,需要根据自己的实际情况来判断是否让元素强行更新,在react下,默认的元素key应该用元素遍历的map索引值来表达。

列表元素等高的场景 ,可以参考《无限滚动加载解决方案之虚拟滚动(上)》

✿  拓展阅读

fad716aeaeddd4ef7943751e952d6fca.png

作者|安笺

编辑|橙子君

出品|阿里巴巴新零售淘系技术

2bd5aae0d61d40b23827c3e436521e2a.png

8efb4301ea04ce7d5fbcc33bc96fd536.png

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值