虚拟滚动技术及其对性能的影响

虚拟滚动是一种前端技术,用于优化包含大量数据的长列表的性能。通过仅在用户可视范围内渲染元素,虚拟滚动显著减少了页面上的 DOM 元素数量。 这种技术不仅提高了渲染效率,还降低了页面的内存占用。

减少 DOM 元素如何提高性能?

  1. 减少渲染成本: 每个 DOM 元素都需要浏览器计算样式、进行布局并绘制到屏幕上。减少 DOM 元素数量意味着浏览器需要处理的工作量更小,从而提高页面加载和渲染速度。

  2. 降低内存占用: DOM 元素越多,页面占用的内存越大。虚拟滚动通过限制 DOM 元素的数量,有效降低了页面的内存占用。

  3. 提高交互响应: 页面上的 DOM 元素越多,浏览器处理事件(如点击、滚动)所需的时间越长。减少 DOM 元素能够提高页面响应用户交互的速度。

量化虚拟滚动对性能的提升

具体性能提升的程度取决于多种因素,包括列表的大小、元素的复杂度以及浏览器的渲染能力。以下是一些典型的性能提升数据:

  • 在长列表(例如,10000项以上)的情况下,使用虚拟滚动技术可以将初始渲染时间减少超过 50%。

  • 内存占用方面,虚拟滚动可以降低约 60%-75% 的内存使用量。对于包含大量高质量图像或复杂结构的列表,这一数字可能更高。

  • 用户滚动和交互的响应时间可减少 70% 以上,特别是在低性能设备或老旧的浏览器上表现更为明显。

原生 JavaScript 实现虚拟滚动

在不使用第三方库的情况下,可以通过原生 JavaScript 实现虚拟滚动。

实现步骤

  1. 创建基本HTML结构: 创建一个容器,用于显示列表项。

    html 复制代码
    <div id="scrollContainer" style="height: 500px; overflow-y: scroll;">
        <div id="listContent"></div>
    </div>
  2. 用 JavaScript 动态加载内容: 当用户滚动时,动态地在 listContent 中添加或移除元素。

    javascript 复制代码
    const container = document.getElementById('scrollContainer');
    const listContent = document.getElementById('listContent');
    const totalItems = 10000; // 假设总项数为10000
    const itemHeight = 50; // 每项的高度
    
    function renderVisibleItems() {
        const scrollTop = container.scrollTop;
        const visibleCount = Math.ceil(container.clientHeight / itemHeight);
        const startIdx = Math.floor(scrollTop / itemHeight);
        const endIdx = startIdx + visibleCount;
    
        // 清空现有内容
        listContent.innerHTML = '';
    
        // 仅添加可见项
        for (let i = startIdx; i <= endIdx; i++) {
            const item = document.createElement('div');
            item.style.height = `${itemHeight}px`;
            item.innerText = `Item ${i}`;
            listContent.appendChild(item);
        }
    
        listContent.style.paddingTop = `${startIdx * itemHeight}px`;
    }
    
    container.addEventListener('scroll', renderVisibleItems);
    renderVisibleItems(); // 初始渲染

结论

虚拟滚动技术通过减少页面上渲染的 DOM 元素数量,优化了大数据列表的性能。使用原生 JavaScript 实现虚拟滚动是一种有效的方法,尤其适合不依赖于第三方库的场景。虽然实现起来比使用专门的库更为复杂,但它提供了更深层次的控制和定制性,使开发者能够根据具体需求精确调整滚动行为和性能。


English version: Visual Scrolling Technique And It's Influence on Performance

Virtual scrolling is a front-end technique used to optimize the performance of long lists containing a large amount of data. By rendering elements only within the user's visible range, virtual scrolling significantly reduces the number of DOM elements on a page. This technique not only improves rendering efficiency but also reduces the page's memory usage.

How Does Reducing DOM Elements Improve Performance?

  1. Reduced Rendering Cost: Each DOM element requires the browser to compute styles, layout, and draw to the screen. Reducing the number of DOM elements means less work for the browser, thereby speeding up page loading and rendering.

  2. Lower Memory Usage: The more DOM elements a page has, the more memory it consumes. Virtual scrolling reduces memory usage by limiting the number of DOM elements.

  3. Improved Interaction Response: The more DOM elements on a page, the longer it takes the browser to handle events like clicks and scrolling. Reducing DOM elements can enhance the page's responsiveness to user interactions.

Quantifying the Performance Enhancement of Virtual Scrolling

The extent of performance improvement depends on several factors, including the size of the list, the complexity of the elements, and the browser's rendering capabilities. Here are some typical performance enhancement statistics:

  • In the case of long lists (e.g., over 10,000 items), using virtual scrolling can reduce initial rendering time by over 50%.

  • In terms of memory usage, virtual scrolling can reduce memory consumption by about 60%-75%. For lists containing a large number of high-quality images or complex structures, this figure may be higher.

  • Response time for user scrolling and interactions can be reduced by over 70%, especially noticeable on low-performance devices or older browsers.

Implementing Virtual Scrolling with Native JavaScript

In the absence of third-party libraries, virtual scrolling can be implemented with native JavaScript.

Implementation Steps

  1. Create Basic HTML Structure: Create a container for displaying list items.

    html 复制代码
    <div id="scrollContainer" style="height: 500px; overflow-y: scroll;">
        <div id="listContent"></div>
    </div>
  2. Dynamically Load Content with JavaScript: As the user scrolls, dynamically add or remove elements in listContent.

    javascript 复制代码
    const container = document.getElementById('scrollContainer');
    const listContent = document.getElementById('listContent');
    const totalItems = 10000; // Assuming a total of 10,000 items
    const itemHeight = 50; // Height of each item
    
    function renderVisibleItems() {
        const scrollTop = container.scrollTop;
        const visibleCount = Math.ceil(container.clientHeight / itemHeight);
        const startIdx = Math.floor(scrollTop / itemHeight);
        const endIdx = startIdx + visibleCount;
    
        // Clear existing content
        listContent.innerHTML = '';
    
        // Add only visible items
        for (let i = startIdx; i <= endIdx; i++) {
            const item = document.createElement('div');
            item.style.height = `${itemHeight}px`;
            item.innerText = `Item ${i}`;
            listContent.appendChild(item);
        }
    
        listContent.style.paddingTop = `${startIdx * itemHeight}px`;
    }
    
    container.addEventListener('scroll', renderVisibleItems);
    renderVisibleItems(); // Initial rendering

Conclusion

Virtual scrolling technology significantly reduces the number of DOM elements rendered on a page, optimizing the performance of large data lists. Implementing virtual scrolling with native JavaScript is an effective method, particularly suitable for scenarios that do not rely on third-party libraries. While the implementation is more complex than using specialized libraries, it provides deeper control and customization, allowing developers to precisely adjust scrolling behavior and performance to specific needs.

相关推荐
Moment8 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
爱敲代码的小鱼9 小时前
AJAX(异步交互的技术来实现从服务端中获取数据):
前端·javascript·ajax
铅笔侠_小龙虾11 小时前
Flutter 实战: 计算器
开发语言·javascript·flutter
大模型玩家七七11 小时前
梯度累积真的省显存吗?它换走的是什么成本
java·javascript·数据库·人工智能·深度学习
2501_9447114311 小时前
JS 对象遍历全解析
开发语言·前端·javascript
发现一只大呆瓜12 小时前
虚拟列表:支持“向上加载”的历史消息(Vue 3 & React 双版本)
前端·javascript·面试
阔皮大师12 小时前
INote轻量文本编辑器
java·javascript·python·c#
lbb 小魔仙12 小时前
【HarmonyOS实战】React Native 表单实战:自定义 useReactHookForm 高性能验证
javascript·react native·react.js
_codemonster12 小时前
Vue的三种使用方式对比
前端·javascript·vue.js
全栈前端老曹13 小时前
【MongoDB】Node.js 集成 —— Mongoose ORM、Schema 设计、Model 操作
前端·javascript·数据库·mongodb·node.js·nosql·全栈