React中使用LazyBuilder实现页面懒加载方法一

前言:

在一个表格中,需要展示100条数据,当每条数据里面需要承载的内容很多,需要渲染的元素也很多的时候,容易造成页面加载的速度很慢,不能给用户提供很好的体验时,懒加载是优化页面加载速度的方法之一。

策略:

前端在接受到api返回的数据的时候,可以先根据数据总的条数进行遍历,给每一项初始化简单的dom进行渲染占位,通过IntersectionObserver 对每一项元素进行监听,当初始dom出现在页面视口的时候,需要替换掉初始dom,渲染真实dom,同样,在初始dom隐藏在页面视口后,我们再去替换掉真实dom,渲染初始dom。这样可以实现:只有出现在视口内的元素才渲染真实的dom,在视口以外的元素都渲染初始dom,首次加载多少个真实dom,取决于可视区域跟初始dom的高度

React中使用LazyBuilder实现页面懒加载方法二

与方法二不同之处:

方法一:元素出现在可视区域内,即渲染真实dom,一旦消失在可视区域内,即渲染初始dom

方法二:元素只要出现在可视区域内一次,即渲染真实dom,并且取消对该dom的监听,只需加载一次

LazyBuilder.jsx

javascript 复制代码
import React, { Component, createRef } from "react";
class LazyBuilder extends Component {
  static defaultProps = {
      initComponent: null,
      initHeight: null,
      controller: null,
      className: null,
      style: null,
  }
  /**
   * @param {Object} props
   * @param {JSX.Element} [props.initComponent] - 默认组件
   * @param {Number} [props.initHeight] - 组件高度
   * @param {LazyController} [props.controller] - LazyController
   */
  constructor(props) {
    super(props);
    this._ref = createRef();
    this.controller = this.props.controller instanceof LazyController ? this.props.controller : new LazyController();
    this.state = {
        isLoading: undefined,
        firstIsLoading: true, // 作用:在页面进行初始渲染时,所有的项都设置初始dom
        initStyle: {
          width: "100%",
          height: props.initHeight
        },
        key: `lazy_${Math.random().toString(16).slice(2)}`,
    }
  }

  componentDidMount() {
    // 页面初始化时,对所有元素进行绑定监听
    this.controller.observe(this._ref.current, this.updateShowElement.bind(this));
  }

  updateShowElement = (type) => {
    const {initHeight} = this.props
    if(type == 1){
      // 元素出现在视口以内
      this.setState({
        isLoading: false,
        firstIsLoading: false,
        initStyle: null,
      });
    } else if(type == 2) {
      // 元素出现在视口以外
      this.setState({
        isLoading: true,
        initStyle: {
          width: "100%",
          height: initHeight
        },
      });
    }
  }

  render () {
    const { children, initComponent } = this.props;
    const { isLoading, initStyle, firstIsLoading} = this.state;
    const className = ["lazy-builder-item", this.props.className].filter(item => typeof item === "string").join("\s");
    return (
        <div id={this.state.key} ref={this._ref} className={className} style={Object.assign({}, initStyle, this.props.style)}>
          {
            firstIsLoading
            ? initComponent
            : isLoading ? initComponent : children
          }
        </div>
    );
  }
}

class LazyController {
  constructor(){

    // 定义map来存储所有的dom项
    this._map = new Map();

    // IntersectionObserver 对每一项元素进行监听
    this.observer = new IntersectionObserver((entries) => {
      for (const entry of entries) {
        const updateShowElement = this._map.get(entry.target);
        // isIntersecting: true - 出现在视口    false - 隐藏(视口以外)
        if (entry.isIntersecting) {
          if (typeof updateShowElement === "function") {
            updateShowElement(1)
          }
        } else {
          if (typeof updateShowElement === "function") {
            updateShowElement(2)
          }
        }
      }
    });
  }

  // 观察指定DOM
  observe = (target, callback) => {
    if (this.observer && !this.has(target)) {
      // 初始化时,将每一项保存在map中
      this._map.set(target, callback);
      this.observer.observe(target);
    }
  }

  // 判断一个DOM是否正在被观察
  has = (target) => {
    return this._map.has(target);
  }

}

export {
  LazyBuilder,
  LazyController,
}

cp.jsx

javascript 复制代码
import React, {Component} from 'react';
import { LazyBuilder, LazyController } from './LazyBuilder'
export default class  Cp extends Component {
  constructor(props){
    super(props)

    // 创建controller
    this.controller = new LazyController();
    this.state = {
      // 模拟数据
      dataList: new Array(100).fill().map((item, index) => index + 1)
    }
  }

  render(){
    const {dataList} = this.state
    return (
      <div>
        {
          Array.isArray(dataList) && dataList.length > 0
          ? dataList.map((item, index) => {
            return <LazyBuilder 
                    key={index}
                    initHeight={100} // 初始dom高度
                    controller={this.controller} // controller
                  >
                    <div style={{width: '100%', height: '200px'}}>{`第${item}个元素`}</div>
                  </LazyBuilder>
          })
          : null
        }
      </div>
    )
  }
}

效果

页面刚加载时,只有前面几条数据在视口内

经过滚动后

相关推荐
漂流瓶jz6 小时前
Webpack如何实现万物皆可import?loader的使用/配置/手写实践
前端·javascript·webpack
ZC跨境爬虫6 小时前
跟着 MDN 学CSS day_41:显式轨道、隐式网格与区域命名放置
前端·javascript·css·ui·交互
weelinking6 小时前
【产品】12_接入数据库——让数据永久保存
jvm·数据库·python·react.js·数据挖掘·前端框架·产品经理
修己xj7 小时前
告别手动存图!这款叫 Fatkun 的浏览器插件,简直是素材收集神器
前端
袋鼠云数栈7 小时前
从前端到基础设施,ACOS 如何打通企业全链路可观测
运维·前端·人工智能·数据治理·数据智能
AskHarries7 小时前
系统提示词、开发者指令和用户输入的优先级
java·前端·数据库
Moment8 小时前
长上下文会最终杀死 Rag 吗?
前端·javascript·后端
qcx238 小时前
【系统学AI】25 论文导读 ①:两篇改变 AI 的开山之作——Attention Is All You Need & ReAct
前端·人工智能·react.js·transformer
kyriewen9 小时前
大文件上传最全指南:分片、断点续传、秒传,一篇就够了
前端·javascript·面试
郑洁文10 小时前
基于Python的Web命令执行漏洞自动化检测系统
前端·python·网络安全·自动化