:: krowemoh

Sunday | 20 APR 2025
Posts Links Other About Now

previous
next

Sveltekit Limitations

2025-04-18

I thought I already had a limitations document but apparently not. It's in another private file called Konsta-Limitations. Not sure why I made it private but for now I'll leave it there.

Back Button

A major limitation of sveltekit is that the back button doesn't rely on the browser cache but rather svelte tries to hydrate the page. What this means that if you navigate to a page and then press the back button, the the old page is being reloaded and the load call is being done again.

This means the back button can't put the scroll where it should be as the page is being rendered brand new.

This is a solved problem for browsers but now its a problem in sveltekit. Mix in konsta ui and you have multiple levels of things to try and get the default behavior of pressing back and being at the right scroll position. This is frustrating.

The snapshot option in sveltekit works to bring the scroll position back by saving it before you leave the page but it means that you have to wait for the page to render before changing the scroll. This means there is a slight flash of content before the scroll fixes itself.

My current fix is this:

https://github.com/konstaui/konsta/issues/226

<script>
    let scrollX = 0
    let scrollY = 0
    
    export const snapshot = {
        capture: () => {
            let y = document.getElementById('myPage').scrollTop;
            return JSON.stringify({scrollPosition: { y }})
        },
        restore: (snapshotJSON) => {
            const snapshot = JSON.parse(snapshotJSON)
            if (snapshot.scrollPosition) {
                scrollY = snapshot.scrollPosition.y
            }
        },
    };
    
    onMount(() => {
        setTimeout(() => {
            document.getElementById('myPage').scrollTo(scrollX, scrollY)
        }, 500)
    });
</script>

<Page id="myPage"> 
</Page>