I see many websites such as gitHub changing it's html content and URL
without refreshing pages.
I find one possible way to do this in 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 is working fine even you go back or forward in browser.
But the problem is that when you refresh page it only shows the file which is being refreshed. For example, if you refresh the about.html
then only the following will show: This is the about page
.
Unlike the gitHub it can't show the complete page. As you see in gitHub
, even you refresh a page it will show the page same as how it was before refreshing.
How can I do that?
Thanks...