Change html content and url without page reload

I see a lot of sites like gitHub , changing its html content and URLwithout refreshing the pages.
I find one possible way to do this at HTML Histroy API.
Here is the code.
HTML

 <div class="container">
 <div class="row">
    <ul class="nav navbar-nav">
        <li><a href="home.html" class="historyAPI">Home</a></li>
        <li><a href="about.html" class="historyAPI">About</a></li>
        <li><a href="contact.html" class="historyAPI">Contact</a></li>
    </ul>
 </div>
 <div class="row">
    <div class="col-md-6">
        <div class="well">
            Click on Links above to see history API usage using   <code>pushState</code> method.
        </div>
    </div>
    <div class="row">    
        <div class="jumbotron" id="contentHolder">
            <h1>Home!</h1>
            <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry.</p>
        </div>
    </div>
   </div>
  </div>  

home.html

 This is home page  

about.html

 This is about page  

contact.html

 That one is content page  

JAVASCRIPT

 <script type="text/javascript">
jQuery('document').ready(function(){

    jQuery('.historyAPI').on('click', function(e){
        e.preventDefault();
        var href = $(this).attr('href');

        // Getting Content
        getContent(href, true);

        jQuery('.historyAPI').removeClass('active');
        $(this).addClass('active');
    });

});

// Adding popstate event listener to handle browser back button  
window.addEventListener("popstate", function(e) {

    // Get State value using e.state
    getContent(location.pathname, false);
});

function getContent(url, addEntry) {
    $.get(url)
    .done(function( data ) {

        // Updating Content on Page
        $('#contentHolder').html(data);

        if(addEntry == true) {
            // Add History Entry using pushState
            history.pushState(null, null, url); 
        }

    });
}
 </script>  

This code works fine even if you return or go to the browser.
But the problem is that when you refresh the page, it shows only the updated file. For example, if you upgrade about.html, then displays only the following: This is the about page.

gitHub . gitHub, , , .

?

...

+4
4
0

DOM , .

XMLHTTPRequest Ajax .

, URL, . Angular JS - , routing .

0

/ .

0

- , . , .

0

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


All Articles