Skip to content

Instantly share code, notes, and snippets.

@abbotto
Last active August 29, 2015 14:24
Show Gist options
  • Select an option

  • Save abbotto/0f6ad240b6b5c5f9923a to your computer and use it in GitHub Desktop.

Select an option

Save abbotto/0f6ad240b6b5c5f9923a to your computer and use it in GitHub Desktop.
Use the History API with jQuery AJAX
// define asset paths
viewPath = 'view/';
clientPath = 'client/';
designPath = 'design/';
// cache some vars
$doc = $(document);
$app = $("#application");
// initial page view
defaultPage = 'splash.html';
// 404 redirect
fourZeroFour = '404.html';
// dynamically obtain a list of current views via a php file
$.get(viewPath + "views.php", function(data) {
localStorage['views'] = data;
});
var views = localStorage['views'];
localStorage.removeItem['views'];
// default web directory for the application
rootDirectory = window.location.pathname.replace(window.location.pathname.split("/").pop(), "");
if (location.pathname.search('html') > -1) {
href = location.pathname.split("/").pop();
if (localStorage['referrerView'] !== (viewPath + href)) {
history.pushState({}, "URL", href);
}
var href = viewPath + href;
} else {
if (localStorage['referrerView'] !== (viewPath + defaultPage)) {
history.pushState({}, "URL", rootDirectory);
}
var href = viewPath + defaultPage;
}
// loads the requested page
_loadView = function(href) {
// because we redirect to index.php on 404, xhr.state() will always equal "resolved"
// so, we need to creatively identify a 404 redirect
viewsArr = JSON.parse(views);
if (viewsArr.indexOf(href) === -1 && location.pathname !== rootDirectory) {
// 404
href = viewPath + fourZeroFour;
}
if (location.pathname !== rootDirectory) {
href = location.pathname.split("/").pop();
if (viewsArr.indexOf(href) === -1) {
// 404
href = fourZeroFour;
}
href = viewPath + href;
}
$app.load(href, function(response, status, xhr) {
localStorage['referrerView'] = href;
$('body').trigger('viewReady');
});
};
// when back/forward is clicked
$(window).on("popstate", function(e) {
_loadView(location.href);
});
// when [data-view] is clicked load new view
$(document).on("click", "[data-view]", function() {
url = $(this).attr("data-view");
href = url;
// redirect to external page if one is passed
if (url.indexOf('http') > -1) {
window.open(url);
return;
}
history.pushState({}, '', href);
_loadView(href);
return false;
});
// initial page view
//console.log('Attempting to load: ' + href);
_loadView(href);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment