Performance: Virtual scrolling for large lists
HIGH IMPACT
Virtual scrolling improves page load speed and rendering performance by only rendering visible list items, reducing DOM size and layout calculations.
<template> <div ref="scrollContainer" style="height: 400px; overflow-y: auto;"> <div :style="{ height: totalHeight + 'px', position: 'relative' }"> <div v-for="item in visibleItems" :key="item.id" :style="{ position: 'absolute', top: itemPositions[item.id] + 'px', height: itemHeight + 'px', width: '100%' }" > {{ item.name }} </div> </div> </div> </template> <script setup> import { ref, computed, onMounted, onUnmounted } from 'vue' const items = Array.from({ length: 10000 }, (_, i) => ({ id: i, name: `Item ${i}` })) const itemHeight = 30 const scrollTop = ref(0) const containerHeight = 400 const visibleCount = Math.ceil(containerHeight / itemHeight) + 1 const visibleItems = computed(() => { const startIndex = Math.floor(scrollTop.value / itemHeight) return items.slice(startIndex, startIndex + visibleCount) }) const itemPositions = {} items.forEach((item, index) => { itemPositions[item.id] = index * itemHeight }) const totalHeight = items.length * itemHeight const scrollContainer = ref(null) function onScroll() { scrollTop.value = scrollContainer.value.scrollTop } onMounted(() => { scrollContainer.value.addEventListener('scroll', onScroll) }) onUnmounted(() => { scrollContainer.value.removeEventListener('scroll', onScroll) }) </script>
<template>
<ul>
<li v-for="item in items" :key="item.id">{{ item.name }}</li>
</ul>
</template>
<script setup>
const items = Array.from({ length: 10000 }, (_, i) => ({ id: i, name: `Item ${i}` }))
</script>| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Render all items | 10,000 nodes created | 10,000 reflows | High paint cost | [X] Bad |
| Virtual scrolling | ~15 nodes created | ~15 reflows | Low paint cost | [OK] Good |