📜 ⬆️ ⬇️

Stop using location.hash, long live the HTML5 History API!

For many years, location.hash been a way in an AJAX application to make the Back / Forward buttons work and, for example, add a specific state of a page to your favorites and return to it later.

Now that HTML5 is considered the norm, it's time to turn your attention to the History API and forget about location.hash . The HTML5 History API is easier to understand and allows you to make the URL a little prettier (without cracking # or #! If you are dealing with indexing ajax applications ).

Browser Support


image

Of course, IE caught up with good browsers only to version 10. Personally, in my projects I don’t support IE <= 9 users, but this does not mean that you have good customers too or you are your own customer :) In any case, adding support for old browsers is no problem, there are a large number of libraries with hash-fallback , for example HTML5 History API , presented by the author on Habrahabr.
')

Principle of operation


I can put the whole essence of the History API in one commented piece of code:
 //  back/forward  window.onpopstate = function(event) { console.log("location: " + location.href + ", state: " + JSON.stringify(event.state)); }; //    history.pushState({page: 1}, "title 1", "?page=1"); history.pushState({page: 2}, "title 2", "?page=2"); //    history.replaceState({page: 3}, "title 3", "?page=3"); history.back(); // location: http://example.com/example.html?page=1, state: {"page":1} history.back(); // location: http://example.com/example.html, state: null history.go(2); // location: http://example.com/example.html?page=3, state: {"page":3} console.log(history.state) // Object {page: 3} 

Well, really easy? :) Do not torment yourself and your colleagues more with work with location.hash . He has a worthy successor - HTML5 History API.

Source: https://habr.com/ru/post/200106/


All Articles