Skip to content

Commit acf652f

Browse files
authored
feat(ViewTransitions): use scrollend instead of scroll where supported (#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
1 parent a35c21c commit acf652f

File tree

2 files changed

+15
-12
lines changed

2 files changed

+15
-12
lines changed

.changeset/long-chefs-jump.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'astro': patch
3+
---
4+
5+
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.

packages/astro/components/ViewTransitions.astro

Lines changed: 10 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -385,17 +385,15 @@ const { fallback = 'animate' } = Astro.props as Props;
385385
});
386386
addEventListener('load', onPageLoad);
387387
// There's not a good way to record scroll position before a back button.
388-
// So the way we do it is by listening to scroll and just continuously recording it.
389-
addEventListener(
390-
'scroll',
391-
throttle(() => {
392-
// only updste history entries that are managed by us
393-
// leave other entries alone and do not accidently add state.
394-
if (history.state) {
395-
persistState({ ...history.state, scrollY });
396-
}
397-
}, 300),
398-
{ passive: true }
399-
);
388+
// So the way we do it is by listening to scrollend if supported, and if not continuously record the scroll position.
389+
const updateState = () => {
390+
// only update history entries that are managed by us
391+
// leave other entries alone and do not accidently add state.
392+
if (history.state) {
393+
persistState({ ...history.state, scrollY });
394+
}
395+
}
396+
if ('onscrollend' in window) addEventListener('scrollend', updateState);
397+
else addEventListener('scroll', throttle(updateState, 300));
400398
}
401399
</script>

0 commit comments

Comments
 (0)