- How to deal with page refresh when using HTML5 History?
- document.addEventListener('DOMContentLoaded', init, false);
- function hasBrowserHistory(){return !!(window.history && history.pushState);}
- function updateHistory(url, replaceHistory) {
- //Create a page path
- var path = "?page=" + url.split(".")[0];
- var object = {
- data: url
- };
- if(replaceHistory){
- //alert('as');
- /*
- If this is the first page we are loading
- replace the current history item.
- */
- history.replaceState(object, null, path);
- }else{
- //alert('qw');
- /*
- If we got here by clicking one of the links
- add a new item to the browser history
- */
- history.pushState(object, null, path);
- }
- }
- function loadPage(whichPage, replaceHistory) {
- $('#contentCol').load(whichPage);
- updateHistory(whichPage, replaceHistory);
- }
- function historyPopStateHandler(e) {
- //var state = history.state;
- if (e.state == null) {
- alert(e.state.url);
- }
- if(e.state != null) {
- loadPage(e.state.data, true);
- }
- }
- function getUrlVars() {
- var vars = [], hash;
- var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
- for(var i = 0; i < hashes.length; i++)
- {
- hash = hashes[i].split('=');
- vars.push(hash[0]);
- vars[hash[0]] = hash[1];
- }
- return vars;
- }
- function init() {
- //Check if the history API is available
- if(!hasBrowserHistory()){
- alert('Sorry dude, your browser does not support the history API');
- return;
- }
- //Check if we have any url params (e.g bookmark or reload)
- var params = getUrlVars();
- if(params['page'] != undefined && params['page'] != null){
- //Load the holder page with the correct content
- loadPage(params['page'] + ".jsp", true);
- }else{
- //Load the default page
- loadPage('loadcourses.jsp', true);
- }
- //Setup listeners for the links
- jQuery('nav > a').click(function(e){
- e.preventDefault();
- loadPage(jQuery(e.target).attr('href'), false);
- });
- //Setup listeners for the history events
- window.addEventListener('popstate', historyPopStateHandler);
- }