Working With The History Api; Pushing & Popping
The history API allows us to update the browsers URL and history without causing a page refresh. This is a good way to update only necessary components, without causing a full page reload. This means a faster load time for the users and an overall smoother experience for our users.
Pushstate takes 3 arguments; The first argument is the data we’ll need if the state of the web page changes, for instance whenever someone presses the back or forwards button in their browser. Note that in Firefox this data is limited to 640k characters. Title is the second argument which can be a string, but at the time of writing, every browser simply ignores it. This final argument is the URL we want to appear in the address bar.
history.pushState(([page data], [page title], [page URL]);
While the pushState() method is used when navigating forward from A to B, the History API also provides a “popstate” event—used to mange back/forward button navigation. The event’s “state” property maps to the data passed as the first argument to pushState().
If the user presses the back button to return to the initial point from which they first navigated via pushState, the “state” property of the “popstate” event will be undefined which causes the back button to fail. We need to set the state for the initial, full-page load use the replaceState() method. It accepts the same arguments as the pushState() method.
history.replaceState([page data], [page title], [page URL])
As always, make sure you check the current browser support and make sure to provide a fall back for browsers that don’t support this feature.
I’ve seen many great uses for pushstate, and used it myself also. It’s a really great way to improve web performance, reducing full page loads for users and only updating necessary content. If you want to know more about this feature, read the full history API spec.