Using History.js with AJAX

Date Posted: April 28, 2016, 10:37 pm


Over the past decade, web applications have evolved to make heavy use of JavaScript in order to dynamically load content into web pages. One of the big challenges that developers face when creating these applications is preserving an accurate and useful browser history. Without this many of a browsers most used features, like the back and forward buttons, will not work as expected.

Aim

  • To store a history of every dynamically loaded pages.
  • To load dynamic contents base on the URL inputted / pasted directly into the brower’s URL bar.
  • To make the browser’s forward and backward buttons work.
  • To enable sharing of URLs or use them to create links from any HTML document.

History.JS currently supports a lot of JavaScript libraries, but for this example I will only be demonstrating how to use the jQuery version of History.JS in working with dynamic contents.

Demo

Logs

Using History.Log() we can check the data stored to the history of our browser in object representation.

Source Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
    <script type="text/javascript" src="js/jquery.history.js"></script>
   
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
    <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
         
</head>
<body>
    <br />
    <div class = "container">
        <nav class="navbar navbar-default">
            <div id="navbar" class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li><a href="home">Home</a></li>
                    <li><a href="about">About</a></li>
                    <li><a href="contact">Contact</a></li>     
                </ul>  
            </div>
        </nav>
        <div class = "content"></div>
    </div>
</body>

<script type='text/javascript'>
$(function(){
   
    var History = window.History;
   
    if (History.enabled) {
        var page = get_url_value('page');
        var path = page ? page : 'home';
        // Load the page
        load_page_content(path);
    } else {
        return false;
    }

    // Content update and back/forward button handler
    History.Adapter.bind(window, 'statechange', function() {
        var State = History.getState();
        // Do ajax
        load_page_content(State.data.path);
        // Log the history object to your browser's console
        History.log(State);
    });

    // Navigation link handler
    $('body').on('click', 'nav a', function(e) {
        e.preventDefault();
       
        var urlPath = $(this).attr('href');
        var title = $(this).text();
       
        History.pushState({path: urlPath}, title, './?page=' + urlPath); // When we do this, History.Adapter will also execute its contents.       
    });
   
    function load_page_content(page) {
        $.ajax({  
            type: 'post',
            url: page + '.html',
            data: {},                      
            success: function(response) {
                $('.content').html(response);
            }
        });
    }
   
    function get_url_value(variable) {
       var query = window.location.search.substring(1);
       var vars = query.split("&");
       for (var i=0;i<vars.length;i++) {
               var pair = vars[i].split("=");
               if(pair[0] == variable){return pair[1];}
       }
       return(false);
    }
});

</script>
</html>

About author


Carl Victor Fontanos

A fine gentleman specializing in front-end and back-end development with extensive experience building high performance web applications that keeps users engaged and help businesses grow.

 
Hire Me