The scroll event is never fired by Chrome when the page is hidden, despite the page is actually scrolling. That looks like something they implemented to reduce cpu and network usage for pages that are not visible.
Is there a way to workaround this behavior, even using Chrome's flags or extensions? I need the "scroll" event to trigger, because that is what I am testing.
setInterval(() => {
window.scrollBy(0, 100);
// scrolls indefinitely even when the page is hidden
}, 1000);
addEventListener("scroll", () => {
console.log("scroll " + document.documentElement.scrollTop);
// however, this gets fired only if document.hidden is false
});
This is actually in accordance with the specs.
The scroll event is to be fired as part of the update the rendering steps of the event-loop. This update the rendering can be short-cut per its steps 2 to 5 where the browser is free to discard it when it deems the rendering would be useless (e.g when the document is hidden).
So even though the scroll did happen, since the rendering didn't happen yet, there is no event to be fired.
Note: In Firefox adding a call to
requestAnimationFramewill force the event to fire for a few seconds, but quickly they'll show Chrome's behavior of throttling all rAF calls until the document is visible again.To workaround this depends on your exact situation.
If you are in control of where the the scroll came from like in your example, then it's quite simple to fire it yourself, it doesn't even require an event.
If you are not responsible for that original
setInterval, but know its frequency, you can also start your own interval in parallel:If you are not sure how it's fired, you could go as far as to overwrite all scrolling methods and setters so that they also execute your callback.
And if you still need to find whether an user scroll did happen, you could temper all these workarounds by calling the callback only when
document.hiddenis true, and let thescrollevent handle the others.PS: If you are worried about smooth-scrolling, note that browsers don't update the smoothed scroll position when the document is hidden.