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;
const fragment = document.createDocumentFragment();
for (let i = 0; i < size; i++) {
const el = document.createElement("div");
el.style.cssText +=
"background:#ccc;height:" +
(itemHeight -
10) +
"px;margin:5px 0;transform: translateY(" +
(itemHeight * ((pageIndex - 1) * size + i)) +
"px);";
el.innerText = data[(pageIndex - 1) * size + i];
fragment.appendChild(el);
}
listEl.appendChild(fragment);
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: pink;
overflow-y: auto;
position: relative;
}
#list > div {
position: absolute;
width: 100%;
}