preface
In some business scenarios, the front end will encounter lists that cannot be paged, and when the list data is large (say, more than 10,000), page performance will be affected. That’s where optimization comes in, and virtual lists are one way to do that.
What is a virtual list
Virtual list is actually an implementation of on-demand display, that is, rendering only the visible area, not rendering or partial rendering of the data in the non-visible area, so as to achieve extremely high rendering performance.
Let’s say we have 10,000 records, but our visible area only shows 6 records, so when we render for the first time, we only need to render these 6 records. When the list is scrolling, we just need to calculate which six records need to be displayed in the visible area, and then delete the list items that exist in the non-visible area.
Implementation approach
We assume that each list item has the same height.
- Calculate the startIndex of the current viewable region
- Calculate the endIndex of the current viewable region
- Calculates the data for the current viewable area and renders it to the page
- Calculate the startIndex data offset startOffset in the entire list and set it to the list
DOM structure is:
<div class="list-view" @scroll="handleScroll">
<div class="list-view-phantom"></div>
<div class="list-view-content">
<! -- list-view-item item-1 -->
<! -- list-view-item item-2 -->
<! -... -->
<! -- list-view-item item-n -->
</div>
</div>
Copy the code
Among them:
- .list-view is a container for visible areas, using relative positioning
- .list-view-phantom uses an invisible element to prop up the list to the total list height, making the list scroll bar appear
- List-view-content Renders the area of the list item, using absolute positioning, with left, right, and top set to 0
Then, in the logical part, we listen for the scroll event of the list-view to obtain the scroll position scrollTop:
- Assuming the viewable area is fixed in height, we call it screenHeight
- Assuming that each item in the list is fixed in height, we call it itemSize
- Suppose the listData is called listData
- Assume that the current scrolling position is called scrollTop
Then we can calculate:
- ListHeight = Listdata.length * itemSize
- VisibleCount = math.ceil (screenHeight/itemSize) visibleCount = math.ceil (screenHeight/itemSize)
- StartIndex = math.floor (scrollTop/itemSize)
- EndIndex of data endIndex = startIndex + visibleCount
- VisibleData = ListData. slice(startIndex,endIndex)
After scrolling, since the render area has been offset relative to the viewable area, I need to get an offset startOffset to offset the render area to the viewable area with style control.
Offset startOffset = scrollTop – (scrollTop % itemSize);
Reference:
- Talk about the realization of the front end virtual list
- “Front-end Advanced” high performance rendering of 100,000 pieces of data (virtual list)