Skip to content

Commit

Permalink
feat(ViewTransitions): use scrollend instead of scroll where supp…
Browse files Browse the repository at this point in the history
…orted (#8156)

* feat(ViewTransitions): use `scrollend` instead of `scroll` where supported

The [scrollend](https://developer.chrome.com/blog/scrollend-a-new-javascript-event/#event-details) mechanism seems like a better way to record the scroll position compared to throttling, so we could use it whenever a browser supports it.

Additionally, I've removed the `{passive}` flag from the `scroll` event, as it does nothing ([source](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener?retiredLocale=de#improving_scrolling_performance_with_passive_listeners:~:text=You%20don%27t%20need%20to%20worry%20about%20the%20value%20of%20passive%20for%20the%20basic%20scroll%20event.%20Since%20it%20can%27t%20be%20canceled%2C%20event%20listeners%20can%27t%20block%20page%20rendering%20anyway.)).

* Create long-chefs-jump.md

* fix typo / update comment
  • Loading branch information
kurtextrem authored Aug 25, 2023
1 parent a35c21c commit acf652f
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 12 deletions.
5 changes: 5 additions & 0 deletions .changeset/long-chefs-jump.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'astro': patch
---

The scrollend mechanism is a better way to record the scroll position compared to throttling, so we now use it whenever a browser supports it.
22 changes: 10 additions & 12 deletions packages/astro/components/ViewTransitions.astro
Original file line number Diff line number Diff line change
Expand Up @@ -385,17 +385,15 @@ const { fallback = 'animate' } = Astro.props as Props;
});
addEventListener('load', onPageLoad);
// There's not a good way to record scroll position before a back button.
// So the way we do it is by listening to scroll and just continuously recording it.
addEventListener(
'scroll',
throttle(() => {
// only updste history entries that are managed by us
// leave other entries alone and do not accidently add state.
if (history.state) {
persistState({ ...history.state, scrollY });
}
}, 300),
{ passive: true }
);
// So the way we do it is by listening to scrollend if supported, and if not continuously record the scroll position.
const updateState = () => {
// only update history entries that are managed by us
// leave other entries alone and do not accidently add state.
if (history.state) {
persistState({ ...history.state, scrollY });
}
}
if ('onscrollend' in window) addEventListener('scrollend', updateState);
else addEventListener('scroll', throttle(updateState, 300));
}
</script>

0 comments on commit acf652f

Please sign in to comment.