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

    For many years, it location.hashwas a way in the AJAX application to make the "Back" / "Forward" buttons work and, for example, add a certain page state 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 it location.hash. HTML5 History API is easier to understand and allows you to make the URL a little more beautiful (without krakozyabra # or #! If you are dealing with indexing an ajax application ).

    Browser support


    Of course, IE caught up with good browsers only to version 10. Personally, I don’t support IE <= 9 users in my projects, but that doesn’t mean that you have good customers either or you’re your own customer :) In any case, adding support for older browsers is not a 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 describe 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:, state: {"page":1}
    history.back(); // location:, state: null
    history.go(2);  // location:, state: {"page":3}
    console.log(history.state) // Object {page: 3}

    Well, really easy? :) Do not torture yourself or your colleagues with location.hash. He has a worthy successor - the HTML5 History API.

    Also popular now: