Pular para o conteúdo
Skillpedia
Sites e telas (frontend)7,8 mil · #13091

virtual-list

O que ela faz

Esta skill explica a rolagem virtual, em que apenas os itens próximos à área visível são desenhados na página. Cobre listas com alturas fixas e com alturas variáveis. É para desenvolvedores que mostram listas muito longas em uma página web.

Quando usar

  • ✓Quando uma lista web tem milhares de itens e a página fica lenta.
  • ✓Quando os itens têm altura fixa e você quer uma lista simples e rápida.
  • ✓Quando os itens têm alturas diferentes e você precisa de uma lista que continue rápida.

Link da skill

https://github.com/HKUDS/AgentPilot/blob/main/openspace/legacy/v1/showcase/skills/virtual-list/SKILL.md

Copie e cole na sua IA (Claude, ChatGPT ou Cursor) pedindo para seguir as instruções.

Como usar

O jeito mais fácil: copie a mensagem e cole na sua IA. Ela lê a skill e segue as instruções.

Mensagem pronta para colar

Use esta skill para me ajudar: https://github.com/HKUDS/AgentPilot/blob/main/openspace/legacy/v1/showcase/skills/virtual-list/SKILL.md Leia o arquivo SKILL.md desse link e siga as instruções dele na minha tarefa.
Quer que a sua IA encontre skills como esta sozinha?Instale o MCP grátis do Skillpedia: uma linha, e ela pesquisa entre 15.000+ skills antes de cada tarefa.Instalar em 1 minuto →

Exemplo do que pedir para a IA

“Pode criar uma lista de dez mil itens na minha página web que role com fluidez?”

5 skills novas por semana. 1 minuto de leitura.

Como funciona

A lista mantém um pequeno conjunto de elementos reutilizáveis da página e desenha apenas as linhas visíveis, além de algumas extras acima e abaixo para evitar tremulação.

Conteúdo técnico (SKILL.md original)

Texto original do autor, em inglês, direto do GitHub.

Virtual List Implementation Skill

Overview

This skill teaches you how to implement a high-performance virtual scrolling list component that can efficiently render thousands or millions of items by only creating DOM nodes for visible items plus a small buffer.

Analysis of Reference Implementation

The VirtualList component from /worldmonitor/src/components/VirtualList.ts demonstrates professional-grade virtual scrolling with the following patterns:

1. Chunk-Based Rendering Pattern

The implementation uses two complementary strategies:

VirtualList (Fixed-Height Items)

  • Item Pool Management: Maintains a pool of reusable DOM elements (PooledElement[])
  • Viewport Calculation: Calculates visible range based on scrollTop, itemHeight, and viewport dimensions
  • Overscan Buffer: Renders extra items above/below viewport (overscan parameter) to prevent flickering during scroll

WindowedList (Variable-Height Items)

  • Chunk-Based Approach: Divides items into chunks (default 10 items per chunk)
  • Lazy Chunk Rendering: Only renders chunks that are visible or within buffer range
  • Placeholder Elements: Creates placeholders for all chunks upfront, renders content on-demand

2. Scroll Listener Optimization

private handleScroll = (): void => {
  if (this.scrollRAF !== null) return;
  
  this.scrollRAF = requestAnimationFrame(() => {
    this.scrollRAF = null;
    if (!this.isDestroyed) {
      this.updateVisibleRange();
    }
  });
};

Key Optimizations:

  • RequestAnimationFrame Throttling: Prevents multiple renders in same frame
  • Passive Listeners: { passive: true } improves scroll performance
  • Debounce Check: Guards against duplicate RAF calls
  • Cleanup Check: Prevents rendering after destruction

3. DOM Recycling Strategy

The implementation uses a sophisticated two-pass recycling algorithm:

Pass 1: Identify Reusable Elements

for (const pooled of this.itemPool) {
  if (pooled.currentIndex >= visibleStart && pooled.currentIndex < visibleEnd) {
    usedIndices.add(pooled.currentIndex);
  }
}

Pass 2: Recycle and Reassign

while (poolIndex < this.itemPool.length) {
  const pooled = this.itemPool[poolIndex]!;
  if (pooled.currentIndex < visibleStart || pooled.currentIndex >= visibleEnd) {
    // Recycle this element
    if (this.onRecycle) {
      this.onRecycle(pooled.element);
    }
    pooled.currentIndex = i;
    this.renderItem(i, pooled.element);
    pooled.element.style.transform = `translateY(${i * this.itemHeight}px)`;
    poolIndex++;
    break;
  }
  poolIndex++;
}

Benefits:

  • Minimizes DOM manipulation
  • Reuses existing elements when possible
  • Allows cleanup of event listeners via onRecycle callback
  • Uses transform: translateY() for GPU-accelerated positioning

4. Performance Optimizations

Spacer Elements for Virtual Height

this.topSpacer.style.height = `${visibleStart * this.itemHeight}px`;
this.bottomSpacer.style.height = `${Math.max(0, (this.totalItems - visibleEnd) * this.itemHeight)}px`;
  • Creates illusion of full list height without rendering all items
  • Maintains accurate scrollbar size and position

Skip Unnecessary Updates

if (visibleStart === this.visibleStart && visibleEnd === this.visibleEnd) {
  return;
}

CSS Positioning Strategy

element.style.position = 'absolute';
element.style.top = '0';
element.style.left = '0';
element.style.right = '0';
element.style.transform = 'translateY(-9999px)'; // Hide off-screen
  • Absolute positioning for precise control
  • Transform for GPU acceleration
  • Off-screen positioning instead of display:none (preserves element state)

ResizeObserver Integration

if (typeof ResizeObserver !== 'undefined') {
  this.resizeObserver = new ResizeObserver(() => {
    if (!this.isDestroyed) {
      this.updateVisibleRange();
    }
  });
  this.resizeObserver.observe(this.viewport);
}
  • Automatically recalculates visible range when viewport resizes
  • Progressive enhancement (checks for browser support)

Complete TypeScript Implementation Template

Below is a simplified but fully functional virtual list implementation that you can drop into any vanilla TypeScript project:

/**
 * SimpleVirtualList - A simplified virtual scrolling implementation
 * 
 * Usage:
 * ```typescript
 * const virtualList = new Sim
Perguntas frequentes

O que é a rolagem virtual?

É um método que desenha apenas os itens que você pode ver, em vez de criar todos os itens na página.

Qual é a diferença entre os dois tipos de lista?

Um é para itens de mesma altura, e o outro é para itens de alturas variáveis, desenhados em blocos.

A rolagem fica fluida?

A skill usa uma atualização temporizada ao rolar, para que a página não faça trabalho extra a cada pequeno movimento.

Detalhes

Descrição original do autor

Implement efficient virtual scrolling for rendering large lists with DOM recycling, chunk-based rendering, and performance optimizations

repo: HKUDS/AgentPilot

Popularidade

Estrelas no GitHub
7,8 mil
Posição no ranking
#13091
Licença
MIT
Atualizada em
01/11/2026

Essa skill é útil?

0

Entre para votar.

Comentários

  • …

Mais skills deste repositório

Skills parecidas