Zhu Wu's Blog

The world is a fine place and worth fighting for.

How to Implement a Perfect Infinite Scroll

Infinite scroll is very popular in web right now because it largely boosts user experience. Thus, I would like to share some tips on implementing a perfect infinite scroll.

Infinite scroll is user friendly, but may not be search engine friendly. We need to help crawlers to discover all the individual items after the first page is loaded. In order to achieve this, build a traditional pagination with page parameter in URL (e.g., example.com/items?page=1), and configure the previous page URL and the next page URL in the <head> for each page to help scrawlers to navigate across the pages. For example, for example.com/items?page=3, put the following in <head>:

<link rel="prev" href="/items?page=2">
<link rel="next" href="/items?page=4">

Infinite scroll helps users to navigate seamlessly, but it can be hard for users to refer back a certain position. Thus, it is recommended to use HTML5 history API to update the current page URL in browser address bar by calling pushState and replaceState accordingly when user scrolls into a different page. In this way, the scrolling history is backed up in browser's history, and user can copy the URL from address bar for their own reference as well.

Normally, we just issue an AJAX call to fetch the next page's contents when the page is scrolled to a certain position. However, this implementation can cause the page to stuck for a while because it needs to wait for the AJAX results to update the page contents. Here is a little trick, which I call it as prefetch-and-cache, to overcome this problem. When the first page is displayed, fetch the second page and cache the contents in a JavaScript variable. Then, render the cached second page contents immediately when the page is scrolled to the second page position. At the same time, fetch the third page, cache the contents, and so on. In this way, we can build a smooth infinite scroll.