Blog.  Engineering at Spinneret.

Using the JavaScript History API on PWA List Pages

You're browsing a list of items on the internet. You click on one to go to the detail page, and you decide you want to look at a different item. You click the back button, and the page it sends you to doesn't even have the item you just clicked on. It shoots you to the bottom of the page, to a "load more" button or something similar.

This is a problem that routinely happens when more items in the list are loaded using AJAX. It decreases usability of your site, and is also a checklist item for having an exemplary PWA, according to Google.

So what is the solution? First, you must modify the server side to accept a query string parameter that controls the number of load more "pages" it should display:

https://my-website.com/my-list-page?loadMorePage=2

For example, if your page by default displays 10 items with a load more button, loadMorePage=2 will make it display 20 items with a load more button.

Next, we will use the Javascript history API to replace the state of the current page when the load more button is clicked. A brief explanation of the history API can be found here.

var loadMoreButton = document.querySelector(".load-more");
loadMoreButton.addEventListener("click", function() {
    //do whatever you have to do to load more items
    var loadMorePageNumber = (document.querySelectorAll(".item") / numOfItemsPerLoadMore) + 1;
    window.history.replaceState({}, "", "?loadMorePage=" + loadMorePageNumber);
});
            

You will notice that now when the load more button is clicked, the url will change in the address bar of your browser. When you visit another page, like the item page, and hit the back button, it will load all the items you had loaded when you visited the next page. And when you click back again, it will take you to the page you were on before the list page, since the history state was replaced instead of pushed onto the history stack.

A simple solution that will improve usability on your site immensely!