Front-end performance optimization: Use virtual scrolling to improve long list rendering performance

In front-end development, we often encounter scenarios where a large amount of data needs to be rendered, such as product lists on e-commerce websites, information flows on social platforms, and so on. When the amount of data is large, directly rendering all the data to the page will cause the page to freeze or even crash. To solve this problem, we can use Virtual Scrolling (Virtual Scrolling) technology to improve long list rendering performance.

This article will introduce the principle of virtual scrolling in detail, and demonstrate how to implement virtual scrolling through a simple example.

Principle of virtual scrolling

The core idea of ​​virtual scrolling is to render only the list items in the visible area, not all the data. When the user scrolls the page, we dynamically calculate the list items in the current viewable area and render only this part of the data. This way, no matter how long the list is, we only need to maintain a certain number of DOM nodes, which greatly improves performance.

Example: Implementing a simple virtual scroll

To demonstrate the implementation of virtual scrolling, we will create a simple long list. Each item in the list consists of a sequence number and a square of a random color.

First, we need to create an array with a lot of data:

javascript复制
const itemCount = 10000;
const items = Array.from({ length: itemCount }, (_, index) => ({
  id: index,
  color: `#${Math.floor(Math.random() * 16777215).toString(16)}`,
}));

Next, we create a VirtualListcomponent called to implement virtual scrolling. This component needs to receive the following parameters:

  • items: list data
  • itemHeight: the height of the list item
  • visibleCount: the number of list items in the visible area
javascript复制
class VirtualList {
  constructor({ items, itemHeight, visibleCount }) {
    this.items = items;
    this.itemHeight = itemHeight;
    this.visibleCount = visibleCount;
    this.init();
  }

  // ...
}

In initthe method, we need to create a container element and set its height and overflow properties. At the same time, we need to create a placeholder element to expand the height of the container so that it can scroll normally.

javascript复制
init() {
  this.container = document.createElement('div');
  this.container.style.height = `${this.visibleCount * this.itemHeight}px`;
  this.container.style.overflow = 'auto';

  this.placeholder = document.createElement('div');
  this.placeholder.style.height = `${this.items.length * this.itemHeight}px`;
  this.container.appendChild(this.placeholder);

  this.renderItems();
  this.bindEvents();
}

In renderItemsthe method, we need to calculate the list items in the current viewable area and render them on the page.

javascript复制
renderItems() {
  const scrollTop = this.container.scrollTop;
  const startIndex = Math.floor(scrollTop / this.itemHeight);
  const endIndex = Math.min(startIndex + this.visibleCount, this.items.length);

  const fragment = document.createDocumentFragment();
  for (let i = startIndex; i < endIndex; i++) {
    const item = this.items[i];
    const itemElement = document.createElement('div');
    itemElement.style.height = `${this.itemHeight}px`;
    itemElement.style.backgroundColor = item.color;
    itemElement.textContent = `Item ${item.id}`;
    fragment.appendChild(itemElement);
  }

  this.container.innerHTML = '';
  this.container.appendChild(this.placeholder);
  this.container.appendChild(fragment);
}

Finally, we need to listen to the container's scrollevent to update the list items as the user scrolls the page.

javascript复制
bindEvents() {
  this.container.addEventListener('scroll', () => {
    this.renderItems();
  });
}

We can now create an VirtualListinstance of and add it to the page:

javascript复制
const virtualList = new VirtualList({
  items,
  itemHeight: 50,
  visibleCount: 10,
});

document.body.appendChild(virtualList.container);

With this simple example, we implement a long list with virtual scrolling. Although this example is relatively simple, it demonstrates the fundamentals of virtual scrolling. In actual projects, we can optimize and extend it as needed.

Summarize

虚拟滚动是一种提升长列表渲染性能的有效方法。通过只渲染可视区域内的列表项,我们可以大大减少 DOM 节点的数量,从而提高页面性能。希望本文能帮助你理解虚拟滚动的原理,并在实际项目中应用这一技术。

Guess you like

Origin juejin.im/post/7250374485567389755