后端一次性返回 十万条数据——分页加载

分页加载

先渲染固定条数数据,当页面滚动到底部时,page+1 渲染后面的固定条数数据

let data = [];
// 模拟十万条数据
for (let i = 0; i < 10000; i++) {
    data.push({ url: '' })
}
        
class RenderEl {
	constructor(options) {
	    const { el, data, page = 1, size = 50, fn } = options;
	    this.el = el || 'body';
	    this.data = data || [];
	    this.page = page;
	    this.size = size;
	    this.total = this.data.length;
	    this.totalPage = Math.ceil(this.total / this.size);
	    this.winH = $(window).innerHeight();
	    this.elFn = typeof fn === "function" ? fn : '';
	}
	// 初始化
	init() {
	    this._render()
	    this._scroll()
	}
	// 渲染数据
   _render() {
        const start = (this.page - 1) * this.size;
        const end = this.page * this.size - 1;
        const newData = this.data.slice(start, end);
        newData.forEach(item => {
            this.elFn(item)
        })
    }
    // 监听滚动到底部
    _scroll() {
        $(document).scroll(() => {
            const h = $(this.el).innerHeight() - $(document).scrollTop();
            if (h <= this.winH && this.page < this.totalPage) {
                this.page++;
                this._render();
            }
        })
    }
}

const renderEl = new RenderEl({
	el: '#lazyBox',
	data,
	fn: (item) => {
	    return $('#lazyBox').append(`${item.url}" class="image">`);
	}
});
renderEl.init();
<div id="lazyBox" class="lazy-box">div>
.lazy-box {
    display: flex;
    flex-direction: column;
}

.image {
    width: 192px;
    height: 120px;
    margin-bottom: 15px;
}

你可能感兴趣的:(JavaScript,前端,css,javascript)