1. What are virtual lists

Long list optimization generally adopts virtual list. Create a container on the page as a viewable area where part of the long list is displayed, rendering the list in the viewable area.

Virtual list simple simulation

<body>
  <div id="container" style="height:150px; overflow:auto">
    <ul id="list"></ul>
    <div id="content-placeholder"></div>
  </div>
</body>
Copy the code
<script> const ITEM_HEIGHT = 30; const ITEM_COUNT = 100; window.onload = function(){ const container = document.querySelector("#container") const containerHeight = container.clientHeight const list = document.querySelector('#list') list.style.height = containerHeight + 'px' const visibleCount = Math.ceil(containerHeight/ITEM_HEIGHT) const placeholder = document.querySelector('#content-placeholder')  list.appendChild(renderNodes(0,visibleCount)) placeholder.style.height = (ITEM_COUNT * ITEM_HEIGHT-containerHeight) + 'px' container.addEventListener('scroll',function(){ list.style.webkitTransform = `translateY(${container.scrollTop}px)`  list.innerHTML = "" const firstIndex = Math.floor(container.scrollTop/ITEM_HEIGHT) list.appendChild(renderNodes(firstIndex, firstIndex + visibleCount)) }) }; function renderNodes(from, to){ const fragment = document.createDocumentFragment(); for(let i = from; i<to; i++){ const el = document.createElement('li') el.style.height = ITEM_HEIGHT + 'px' el.innerText = i+1 fragment.appendChild(el) } return fragment } </script>Copy the code