-
The Github Release feed has been broken for some time, so I create a Svelte app to fetch from github api (https://kieranp.github.io/Github-Releases-Feed/). I noticed that when there has been a lot of releases, the page size was growing past 400MB. In order to reduce page memory, I implemented a change to only insert the description of the release if the release container is scrolled into view. That way, if there are 1000 releases inserted into the page, only the top 4 or so have DOM elements for descriptions, and the rest get added as the user scrolls down. In my use case, this drops the overall page size from 400MB to 120MB. As you can see in the commit, I use IntersectionObserver to accomplish this. In the release component, I bind the release container to a $state variable, then use onMount to create an IntersectionOberserver for that release container. When the IntersectionOberserver fires, it sets loadDescription to true, which, if some other logic passes, then inserts the description DOM element for that release. All of this works fine, no issues. However, this approach causes the creation of 1000+ intersection observers, one for each release container, which is not ideal for performance (1000 observers with 1000 different callbacks). The trouble is, if I create a reusable IntersectionObserver, the only thing the callback has access to is an array of HTMLElements that have been intersected. This means, outside of the context of the release component, I cannot set the loadDescription variable to true. Does Svelte, or might it be able to, provide a way to access the svelte component through the HTMLElement? e.g. The final ideal code would look something like this: helpers.ts const intersectionObserver = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
if (!entry.isIntersecting) return
const component = entry.svelte_component
if (!component || component.loadDescription) return
component.loadDescription = true
intersectionObserver.unobserve(entry)
})
})
export intersectionObserver release.svelte <script lang="ts">
import { onMount } from 'svelte'
import { intersectionObserver } from './helpers.ts'
let releaseDiv = $state<HTMLDivElement>()
let loadDescription = $state(false)
onMount(() => {
intersectionObserver.observe(releaseDiv)
})
</script>
<div bind:this={releaseDiv}>
{#if loadDescription}
...
{/if}
</div> Is this at all possible in the latest version of Svelte? (if so, I've not been able to find it) |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
You can use custom events for this. Example (note, for clarity, I set the threshold to 0.75). |
Beta Was this translation helpful? Give feedback.
You can use custom events for this. Example (note, for clarity, I set the threshold to 0.75).