· 2 min read
Smooth scrolling, but not when SvelteKit navigates
Going to another page started it where the old page was scrolled, then it glided up to the top. A reload halfway down glided back down too. Now a new page…
What we did
- Going to another page started it where the old page was scrolled, then it glided up to the top. A reload halfway down glided back down too. Now a new page starts at the top, and a reload jumps straight back.
scroll-behavior: smoothonly applies underhtml[data-smooth-scroll]. The layout removes the attribute inonNavigateand sets it again one frame afterafterNavigate.
What I learned
scroll-behavior: smoothonhtmlaffects every scroll that doesn't say otherwise, including SvelteKit's own: the jump to the top of a new page, and the jump back to where you were after a reload. Smooth turned both into glides.onNavigateruns before a navigation;afterNavigateruns after it, and also after the first load. SvelteKit has scrolled by then, so arequestAnimationFramelater it's safe to turn smooth scrolling back on.- Links inside a page (the "on this page" nav, the footer hint) aren't SvelteKit navigations, so they still glide.
- Measuring helped: sampling
scrollYevery 250ms after a click showed 1047, 389, 1, 0, a glide. After the fix: 1047, 0.
Links
Next
- Nothing here.