You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用JS Fetch读取本地JSON实现滚动分页批量加载服装图片咨询

服装图片库滚动自动分批加载实现方案

前置修正说明

你原有代码存在语法问题:data[i].images[1, 0, 2, 3].src 中方括号内的逗号表达式会最终返回最后一个值3,实际只会取到images数组的第4个元素,可根据实际需要调整取值索引,下方示例默认取images数组第一个元素的src。

完整实现代码

// 全局变量存储全量数据、当前加载索引、每批加载数量、加载状态锁
let allData = [];
let currentIndex = 0;
const batchSize = 100;
let isLoading = false;

// 初始化拉取全量JSON数据,加载第一批
fetch("dataset_api.json")
    .then(res => res.json())
    .then(data => {
        allData = data;
        // 加载第一批数据
        loadNextBatch();
        // 绑定滚动监听事件
        window.addEventListener('scroll', handleScroll);
    })
    .catch(err => console.error('数据加载失败:', err));

// 加载下一批数据的方法
function loadNextBatch() {
    // 加载中或所有数据加载完成时终止执行
    if (isLoading || currentIndex >= allData.length) return;
    isLoading = true;
    // 计算本次加载的结束索引,避免超出数组长度
    const endIndex = Math.min(currentIndex + batchSize, allData.length);
    let htmlStr = '';
    for (let i = currentIndex; i < endIndex; i++) {
        // 可根据需求修改images数组的索引值
        const imgSrc = allData[i].images[0].src;
        htmlStr += `<div class='grid' data-id='${i}'> <img src='${imgSrc}' class='imggrd' loading='lazy'> </div>`;
    }
    // 一次性批量插入DOM,减少重绘次数提升性能
    $(".app-right").append(htmlStr);
    // 更新当前已加载的索引位置
    currentIndex = endIndex;
    isLoading = false;
    // 全部数据加载完成后移除滚动监听,释放资源
    if (currentIndex >= allData.length) {
        window.removeEventListener('scroll', handleScroll);
    }
}

// 滚动事件处理函数
function handleScroll() {
    // 判断是否滚动到距离底部100px的位置,可自行调整阈值实现提前加载
    const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
    const scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
    const clientHeight = document.documentElement.clientHeight || window.innerHeight;
    if (scrollTop + clientHeight >= scrollHeight - 100) {
        loadNextBatch();
    }
}

可选优化

如果需要移除jQuery依赖,可将代码中DOM插入的部分替换为原生写法:

document.querySelector('.app-right').insertAdjacentHTML('beforeend', htmlStr)

内容的提问来源于stack exchange,提问作者rapiddata2327

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 14:24:03