Virtual List Rendering
JavaScript
Hard
3 views
Problem Description
You have a container #list with fixed height and overflow auto. Render 10000 rows but keep only visible rows in DOM using virtualization. Row height is 30px.
Output Format
No output (DOM change).
Constraints
Assume #list exists and can be styled with height and overflow.
Official Solution
const container=document.getElementById('list');const total=10000;const rowH=30;container.style.overflow='auto';const spacer=document.createElement('div');spacer.style.height=(total*rowH)+'px';spacer.style.position='relative';container.innerHTML='';container.appendChild(spacer);const pool=[];const poolSize=50;for(let i=0;i<poolSize;i++){const row=document.createElement('div');row.style.position='absolute';row.style.left='0';row.style.right='0';row.style.height=rowH+'px';spacer.appendChild(row);pool.push(row);}const render=()=>{const top=container.scrollTop;const start=Math.floor(top/rowH);for(let i=0;i<poolSize;i++){const idx=start+i;if(idx>=total){pool[i].style.display='none';continue;}pool[i].style.display='block';pool[i].style.transform='translateY('+(idx*rowH)+'px)';pool[i].textContent='Row '+(idx+1);}};container.addEventListener('scroll',render,{passive:true});render();
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!