访问另一页后保留浏览器滚动位置

I'm working with JS, JQuery, & PHP and trying to do is solve an infinite scroll problem. The problem is that if you scroll for a long way down the page and it loads more pages with ajax, then click a link to go to a new page, how do you automatically go to that same location in the old page when using the browser back button on the new page?

. New pages are loaded on scroll using ajax.

The solution I've come up with to my question is to store each page along with relevant data prior to navigating away from the page.

The following information is required to maintain scroll position:

  • Page ID (unique to page)
  • Page Data (all of a pages html, careful with data that expires)
  • Paginated Page Number (Only applies if this page is a feed)
  • Current X, Y scroll position
  • Timestamp

When the next page is loaded, the previous information can be stored using local storage. When going back to the previous page, look up the PageID in storage. If it exists, then grab the X or Y coordinate and move page to the position. This takes some strategic thinking because if the page is a lazy-loaded (infinite scroll) type of page or feed, you'll need to have the data already OR be prepared to look up the data based on the position of the page.

The easiest away to build this system is if your whole site is javascript based and you're using the HTML 5 History Api. Preventing full page reloads can help take some of the weight off your server. If you're worried about staying up to date on certain data that expires, you could send the page number to the server and get the respective data to fill in the expired content.

You could get $(window).scrollTop(); value and then save it as a variable in php with the name "pageTop" and call it back on DOM ready:

$(window).load(function() {
    $(window).scrollTo(pageTop);
});

Let me know how that goes.