Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 11th, 2012  |  syntax: None  |  size: 2.00 KB  |  hits: 15  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. How to deal with page refresh when using HTML5 History?
  2. document.addEventListener('DOMContentLoaded', init, false);
  3.  
  4. function hasBrowserHistory(){return !!(window.history && history.pushState);}
  5. function updateHistory(url, replaceHistory) {
  6. //Create a page path
  7. var path  = "?page=" + url.split(".")[0];
  8. var object = {
  9.         data: url
  10.     };
  11.  
  12. if(replaceHistory){
  13.     //alert('as');
  14.     /*
  15.     If this is the first page we are loading
  16.     replace the current history item.
  17.     */
  18.     history.replaceState(object, null, path);
  19. }else{
  20.     //alert('qw');
  21.     /*
  22.     If we got here by clicking one of the links
  23.     add a new item to the browser history
  24.     */
  25.     history.pushState(object, null, path);
  26. }
  27. }
  28.  
  29. function loadPage(whichPage, replaceHistory) {
  30. $('#contentCol').load(whichPage);
  31. updateHistory(whichPage, replaceHistory);
  32. }
  33.  
  34. function historyPopStateHandler(e) {
  35. //var state = history.state;
  36. if (e.state == null) {
  37.     alert(e.state.url);
  38. }
  39. if(e.state != null) {
  40.     loadPage(e.state.data, true);
  41. }
  42. }
  43.  
  44. function getUrlVars() {
  45. var vars = [], hash;
  46. var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
  47. for(var i = 0; i < hashes.length; i++)
  48. {
  49.     hash = hashes[i].split('=');
  50.     vars.push(hash[0]);
  51.     vars[hash[0]] = hash[1];
  52. }
  53. return vars;
  54. }
  55.  
  56. function init() {
  57. //Check if the history API is available
  58. if(!hasBrowserHistory()){
  59.     alert('Sorry dude, your browser does not support the history API');
  60.     return;
  61. }      
  62.  
  63. //Check if we have any url params (e.g bookmark or reload)
  64. var params = getUrlVars();
  65.  
  66. if(params['page'] != undefined && params['page'] != null){
  67.     //Load the holder page with the correct content
  68.     loadPage(params['page'] + ".jsp", true);
  69. }else{
  70.     //Load the default page
  71.     loadPage('loadcourses.jsp', true);
  72. }
  73.  
  74.  
  75. //Setup listeners for the links
  76. jQuery('nav > a').click(function(e){
  77.     e.preventDefault();
  78.     loadPage(jQuery(e.target).attr('href'), false);
  79. });
  80.  
  81. //Setup listeners for the history events
  82. window.addEventListener('popstate', historyPopStateHandler);
  83. }