perf: improve initial virtual list render speed by calculating height once
This commit is contained in:
4 files changed
+57
-29
No files matched your search
@@ -50,6 +50,7 @@
|
||||
let hasMore = $state(true)
|
||||
|
||||
async function loadMore() {
|
||||
console.log(hasMore, loading)
|
||||
if (!hasMore || loading) return
|
||||
|
||||
try {
|
||||
@@ -255,7 +256,14 @@
|
||||
</EndPlaceholder>
|
||||
</div>
|
||||
{/if}
|
||||
<InfiniteScroll window threshold={1000} on:loadMore={loadMore} />
|
||||
<InfiniteScroll
|
||||
window
|
||||
threshold={600}
|
||||
on:loadMore={() => {
|
||||
console.log('loadMore triggered')
|
||||
loadMore()
|
||||
}}
|
||||
/>
|
||||
{/if}
|
||||
{@render children?.()}
|
||||
</ul>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<script lang="ts" generics="T">
|
||||
import { browser } from '$app/environment'
|
||||
import { debounce } from 'mono-svelte/util/time'
|
||||
import { onDestroy, untrack, type Snippet } from 'svelte'
|
||||
import { onDestroy, onMount, untrack, type Snippet } from 'svelte'
|
||||
import type { HTMLAttributes } from 'svelte/elements'
|
||||
import { innerHeight } from 'svelte/reactivity/window'
|
||||
|
||||
@@ -72,15 +72,6 @@
|
||||
let viewportHeight = $state(0)
|
||||
let visibleItems = $state<{ index: number; offset: number }[]>([])
|
||||
|
||||
// Initial render
|
||||
$effect.pre(() => {
|
||||
if (virtualListEl && browser) {
|
||||
untrack(() => {
|
||||
visibleItems = updateVisibleItems()
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
$effect.pre(() => {
|
||||
if (items.length > itemHeights.length) {
|
||||
const missing = items.length - itemHeights.length
|
||||
@@ -88,6 +79,14 @@
|
||||
}
|
||||
})
|
||||
|
||||
$effect(() => {
|
||||
if (items.length) {
|
||||
untrack(() => {
|
||||
visibleItems = updateVisibleItems()
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
function findFirstVisibleIndex(
|
||||
scrollTop: number,
|
||||
cumulativeHeights: number[],
|
||||
@@ -146,7 +145,6 @@
|
||||
const newHeight = entry.contentRect.height
|
||||
if (itemHeights[index] !== newHeight) {
|
||||
itemHeights[index] = newHeight
|
||||
visibleItems = updateVisibleItems()
|
||||
}
|
||||
}
|
||||
}, debounceResize)
|
||||
@@ -179,6 +177,25 @@
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
onMount(() => {
|
||||
if (virtualListEl && browser) {
|
||||
Array.from(virtualListEl.children).forEach(node => {
|
||||
const indexAttr = node.getAttribute('data-index')
|
||||
if (indexAttr === null) return
|
||||
const index = Number(indexAttr)
|
||||
if (isNaN(index)) return
|
||||
|
||||
const newHeight = node.getBoundingClientRect().height
|
||||
if (itemHeights[index] !== newHeight) {
|
||||
itemHeights[index] = newHeight
|
||||
}
|
||||
})
|
||||
untrack(() => {
|
||||
visibleItems = updateVisibleItems()
|
||||
})
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
<svelte:window
|
||||
|
||||
Reference in new issue
Block a user