sveltejs / kit

web development, streamlined
https://kit.svelte.dev
MIT License
18.39k stars 1.88k forks source link

Direct navigation to SSR'd url with anchor scroll bug #11326

Open coryvirok opened 8 months ago

coryvirok commented 8 months ago

I figured I'd open a new bug for this since I think the issue is related to SSR vs CSR anchor scrolling.


I'm also running into this behavior when I directly navigate to a URL with an anchor that is meant to scroll the page down to that id. I haven't found any svelte:window scroll binding (or any scroll binding) in the code on the page in question. But no doubt there is some in other components loaded on other pages. Or, possibly in 3rd party libs like Superforms/Popper.

The behavior I see is:

  1. navigate to http://example.com/#pricing
  2. page loads and immediately begins scrolling to #pricing (I have smooth scrolling enabled)
  3. 2-500ms later, the page immediately sets the window position back to the top

The workaround mentioned above (and pasted below) isn't ideal since it happens after the improper Svelte scrolling and causes visual jitter on the page. But it's better than nothing.

Including @jjagielka workaround from the linked PR:

  // from https://github.com/themesberg/flowbite-svelte/pull/923/files
  onMount(() => {
    // Workaround until https://github.com/sveltejs/kit/issues/2664 is fixed
    if (typeof window !== 'undefined' && window.location.hash) {
      const deepLinkedElement = document.getElementById(window.location.hash.substring(1))
      if (deepLinkedElement) {
        window.setTimeout(() => deepLinkedElement.scrollIntoView(), 100)
      }
    }
  })

Originally posted by @coryvirok in https://github.com/sveltejs/kit/issues/2664#issuecomment-1854622252

coryvirok commented 8 months ago

Here's the client code that resets the scroll to the top on load:

https://github.com/sveltejs/kit/commit/102c59936df9e4936712483cae52fbbbb1f26389#r134931947