Restore scroll position on infinite scroll page

I generally consider infinite scroll to be an antipattern. If you use pagination instead, the browser's behavior is much more predictable.

But if you want infinite scroll w/ back button support, you have only got a few choices:

  • Change the URL as the user scrolls such that the number of records is stored in the URL
  • Store the number of records somewhere else (local storage / cookie)

When the user visits the infinite scroll page, restore the state based on the state you stored in the URL / local storage / wherever.

If I had to do this, I'd try to keep the data in the URL. But if done naively, there are serious flaws with these approaches. Someone malicious could make that number very large, in which case the browser(s) would download way too many records at once.

So, what I'd probably do is only fetch the window of records that matches what they would have seen at their previous scroll position. You can infinitely scroll below it and you can add a "load previous records" or something above it. That would prevent a back-navigation from fetching too many records at once.

Honestly, I think pagination is the answer.

Note, as commented below:

If you aren't concerned about keeping scroll position if the user leaves the site and navigates back, then you can keep the original page in memory (e.g. just hide it and then re-show it when the user navigates back).