如何请求后台1000条数据不卡

(function () {
    const ulContainer = document.getElementById("list-data");
    //const ulContainer = _this.$refs.list;

    // 防御性编程
    if (!ulContainer) return;

    const total = 10000; // 插入数据的总数
    const batchSize = 4; // 每次批量插入的节点个数,个数越多,界面越卡顿
    const batchCount = total / batchSize; // 批处理的次数
    let batchDone = 0;  // 已完成的批处理个数

    function appendItems() {
        // 使用 DocumentFragment 减少 DOM 操作次数,对已有元素不进行回流
        const fragment = document.createDocumentFragment();

        for (let i = 0; i < batchSize; i++) {
            console.log(i);
            const liItem = document.createElement("li");
            liItem.innerText = batchDone * batchSize + i + 1;
            fragment.appendChild(liItem);
        }

        // 每次批处理只修改 1 次 DOM
        ulContainer.appendChild(fragment);
        batchDone++;
        doAppendBatch();
    }

    function doAppendBatch() {
        if (batchDone < batchCount) {
            // 在重绘之前,分批插入新节点
            window.requestAnimationFrame(appendItems);
        }
    }

    // kickoff
    doAppendBatch();

    // 使用 事件委托 ,利用 JavaScript 的事件机制,实现对海量元素的监听,有效减少事件注册的数量
    ulContainer.addEventListener("click", function (e) {
        const target = e.target;

        if (target.tagName === "LI") {
            alert(target.innerText);
        }
    });
})();

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值