JSFiddle - React, Tailwind, and code Playground
by Prathameshsb
HTML
<table>
<thead>
<th>Name</th>
</thead>
<tbody id="tableBody"></tbody>
</table>
JavaScript
// Populate table
let data = []
for (let i=0; i<1000; i++)
data.push({"name": "Jay => " + i})
for (let row of data) {
let rowEl = document.createElement("tr");
rowEl.style.display = "none";
let nameColEl = document.createElement("td");
nameColEl.innerText = row.name;
rowEl.appendChild(nameColEl);
tableBody.appendChild(rowEl);
}
// Lazy load
let bufferRows = 70;
function lazyLoadNext(numRows) {
numRows = Math.min(numRows, tableBody.childNodes.length);
let rowsLoaded = 0;
for (let i = 0; i < tableBody.childNodes.length; i++) {
if (tableBody.childNodes[i].style.display != "none")
continue;
tableBody.childNodes[i].style = "";
rowsLoaded++;
if (rowsLoaded >= numRows)
break;
}
}
function lazyLoadBuffer() {
for (let i = tableBody.childNodes.length - 1; i >= 0; i--) {
if (tableBody.childNodes[i].style.display == "none")
continue;
let rect = tableBody.childNodes[i].getBoundingClientRect();
let viewHeight = window.innerHeight || document.documentElement.clientHeight;
// If we are within 3 screens of the viewport, lazy load more rows
if (rect.bottom <= viewHeight * 3) {
console.log(`Lazy loading ${bufferRows} more rows...`)
lazyLoadNext(bufferRows);
}
break;
}
}
lazyLoadNext(bufferRows);
window.onscroll = lazyLoadBuffer; // optionally debounce