Recently, I was writing a paper which required me to do a little historical background research. Through this I ended up on the website for Encyclopedia Britannica. As I was scrolling the page, I saw something that I hadn’t seen before. As you infinite scrolled down the content page, the URL bar at the top of your browser would update to reflect what section you are in. All of this was done seamlessly without refreshing the browser or anything.
Now, I had seen similar things like this using full page transitions. I had always assumed it was a function of caching or otherwise, but it turns out, its a built in JavaScript method. One that is pretty damn cool.
The methods in question are history.replaceState
and history.pushState
. history.replaceState
, like the name implies, replaces the whole URL with a new one and does not generate a “back” state for you to return to when you hit the back button. If a user was scrolling a page, a website could use this to update a section link as the user scrolled. history.pushState
is a little more interesting, it creates a new history entry and replaces the URL with a new one. This means the back button still functions, and will return you to the previous URL, which also won’t reload the page. This means you could have a whole website that only really loads an entire page once, and just fetches and renders content, and the user would have the same experience as a traditional website.
If you want to see this in action, try the following code snippets on any website:
history.replaceState(null, "Title", "/fakeURL");
history.pushState(null, "Other Title", "/hitTheBackButton");
If this is combined with a listener for the “navigate” event, a full website’s navigation could happen without a reload at all, which is very neat. An example of that could be as follows:
window.navigation.addEventListener("navigate", (e) => {
// fetch content here
})
I may try to screw around with this in the future, but for now, it can live here. If anyone implements a website using something like this, or knows one that does, please email it to me or drop a comment, I’d be very interested to see it in the wild.