Search code examples
javascripthistory.js

Does history.js stay on page after click?


I have a site that uses AJAX to update content. It was developed with progressive enhancement in mind, so it also handles query strings.

URL using PHP:

index.php/products?cat=1&colors=1

URL using AJAX:

index.php/products (Currently stays like this for the life of this page)

Want to end up with this URL:

index.php/products#cat=1&colors=1

I wanted to use history.js but I noticed that for HTML5 browsers it changes the URL to look like the first URL. (!!)

Does history.js merely modify the window.location without actually jumping to the link? If it doesn't, then that means the entire page will be reloaded using PHP, thus defeating the purpose of my script. If this is the case, is there a workaround with this library?


Solution

  • From the docs for history.js, the library provides pushState and replaceState functionality. The Mozilla article on manipulating browser history is worth reading to help understand what this means, and as the article directly says:

    URL — The new history entry's URL is given by this parameter. Note that the browser won't attempt to load this URL after a call to pushState(), but it might attempt to load the URL later, for instance after the user restarts her browser.

    So when you use pushState via any means, including via history.js, the URL will be changed so the user can bookmark the URL to return later and get the same results...but the browser won't load the page as a result of the pushState action.

    Also, understand the difference between pushState and replaceState as both change the URL in the address bar but their impact on history is different.