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

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

作者| 安笺

111.gif

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



滚动方式介绍


原理:用固定个数的元素来模拟无线滚动加载,通过位置的布局来达到滚动后的效果
由于无限滚动的列表元素高度是和产品设计的场景有关,有定高的,也有不定高的。
定高:滚动列表中子元素高度相等。不定高:滚动列表中子元素高度都随机且不相等。
 不定高方案

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

21.jpg

  • 实现原理


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


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


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

22.jpg

  • 实现方式


我们首先定义交叉观察者: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);
      }
    });
  }
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是异步的,导致更新方法触发没跟上,所以需要对滚动事件再做一层的观察,判断是否当前的滚动高度已经更新过了,没更新则通过滚动结束后强行更新,当然,一定要记得对这个滚动事件加一层节流,减少事件触发频率。


  • 兼容问题

23.jpg

在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索引值来表达。


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

相关文章
|
3月前
|
存储 JSON 关系型数据库
【干货满满】解密 API 数据解析:从 JSON 到数据库存储的完整流程
本文详解电商API开发中JSON数据解析与数据库存储的全流程,涵盖数据提取、清洗、转换及优化策略,结合Python实战代码与主流数据库方案,助开发者构建高效、可靠的数据处理管道。
|
9月前
|
前端开发 JavaScript UED
React 滚动条组件 Scrollbar
本文介绍了在 React 中创建和使用滚动条组件的方法。首先,通过设置 `overflow: auto` 等 CSS 属性实现基础滚动功能。接着,推荐了如 `react-custom-scrollbars` 和 `react-perfect-scrollbar` 等第三方库以增强滚动条的功能与外观。针对常见问题,如样式不一致、无法正常工作及性能瓶颈,提供了相应的解决方案,包括自定义样式、确保容器高度和优化渲染逻辑。最后,强调了避免滚动事件绑定错误和不合理嵌套滚动的重要性,帮助开发者打造流畅、美观的用户界面。
532 16
|
关系型数据库 MySQL 开发工具
MySQL双主复制
MySQL双主复制
352 0
|
存储 安全 API
点对点传输
**点对点(P2P)传输技术实现节点间直接数据交换,减少中心服务器依赖,提升效率与速度。优点包括高效、安全、灵活集成。常见应用包括文件共享、实时媒体、宽带接入和VPN。网络拓扑多样,从星形到网状,适应不同场景需求。随着技术发展,P2P将在更多领域发挥作用。**
|
JavaScript 前端开发 开发者
ThreeJs控制模型骨骼实现数字人
这篇文章讲解了如何使用Three.js通过控制模型的骨骼来实现数字人的动态表现,包括加载模型、获取骨骼信息以及通过编程控制骨骼动作的具体方法。
1235 1
|
机器学习/深度学习 算法 自动驾驶
深度学习之分布式智能体学习
基于深度学习的分布式智能体学习是一种针对多智能体系统的机器学习方法,旨在通过多个智能体协作、分布式决策和学习来解决复杂任务。这种方法特别适用于具有大规模数据、分散计算资源、或需要智能体彼此交互的应用场景。
724 4
|
供应链 监控 安全
ERP系统中的库存管理与优化
【7月更文挑战第25天】 ERP系统中的库存管理与优化
1365 2
|
移动开发 前端开发 JavaScript
|
人工智能 前端开发 JavaScript
小说网站|基于Springboot+Vue实现在线小说阅读网站
本项目基于Springboot+Vue开发实现了一个在线小说阅读网站平台。系统设计用户主要有三类:读者、作者、管理员。用户注册时以读者身分进入平台,可以自己修改身分为作者。读者登录系统可以查看并在线阅读发布的小说章节内容,并在线评论、点赞和举报处理,同时可以查看平台发布的小说新闻和平台公告新闻。。作者登录平台除了可以查看小说外,还可以在线发布小说和内容,进行在线创作。所有的信息由平台管理员进行管理操作,包含人员管理、小说管理、章节管理、类型管理、举报管理、评论管理、新闻管理、系统管理(轮播图管理、超链接管理)等。
542 1