console
const count = 10000;
const data = [];
const listEl = document.getElementById("list");
const clientHeight = listEl.offsetHeight;
const itemHeight = 100;
const size = Math.ceil(clientHeight / itemHeight) + 1;
let curPageIndex = 1;
let isLoading = false;
function pageData(total, pageIndex, size) {
window.requestAnimationFrame(() => {
for (let i = 0; i < size; i++) {
data.push(`第${(pageIndex - 1) * size + i}个`);
}
if (pageIndex < total) {
pageData(total, pageIndex + 1, size);
}
});
}
function start() {
const total = Math.ceil(count / size);
pageData(total, 1, size);
setTimeout(()=>{
render(curPageIndex);
}, 500);
}
function render(pageIndex) {
if (isLoading || (pageIndex - 1) * size >= count) return;
isLoading = true;
curPageIndex = pageIndex;
for (let i = 0; i < size; i++) {
const el = document.createElement("div");
el.style.background = "#ccc";
el.style.height = itemHeight - 10 + "px";
el.style.margin = 5 + "px";
el.style.overflow = "hidden";
el.innerText = data[(pageIndex - 1) * size + i];
listEl.appendChild(el);
}
isLoading = false;
}
listEl.addEventListener("scroll", () => {
if (listEl.scrollTop + listEl.clientHeight + 1 >= listEl.scrollHeight) {
console.log("下一页", curPageIndex + 1);
render(curPageIndex + 1);
}
})
<button onclick="start()">start</button>
<div id="list"></div>
#list{
height: 300px;
background: lightgreen;
overflow-y: auto;
position: relative;
}