Use an array to store history.
$(document).ready(function () {
var history = [];
if (!$('#ajax').length) { // Check if index.html was loaded. If not, navigate to index.html and load the hash part with ajax.
document.location = document.location.href.substring(0, document.location.href.lastIndexOf('/') + 1)
+ "#" + document.location.href.substr(document.location.href.lastIndexOf('/') + 1);
history.push(document.location.href.substr(document.location.href.lastIndexOf('/') + 1);
}
if (window.location.hash) // Check if the page is being loaded with a '#'. Load the file.
$('#ajax').load(document.location.href.substr(document.location.href.lastIndexOf('#') + 1), function(){
history.push(document.location.href.substr(document.location.href.lastIndexOf('#') + 1));
});
});
$(document).on("click", "a:not(.regular)", function (e) {
var url = this.href;
if (url.indexOf("https") != -1 || url.indexOf('.html') == -1) // External link or picture
return;
e.preventDefault();
$('#ajax').load(url, function () {
document.location.href = '#' + url.substr(url.lastIndexOf('/') + 1);
history.push(url.substr(url.lastIndexOf('/') + 1);
});
});
$(window).on('popstate', function (e) {
$('#ajax').load(history[history.lastIndexOf(document.location.href)-1], function(){
document.location.href = "#" + history[history.lastIndexOf(document.location.href)-1];
});
});