Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Re-execute js on back without reloading the whole page

Is there a way to re-execute JS without refreshing a page?

Say if I have a parent page and an inside page. When the inside page gets called, it gets called via ajax, replacing the content of the parent page. When user clicks back, I would like to navigate them back to the parent page without having to reload the page. But, the parent page UI relies on javascript so after they click back, I would like to re-execute the parent page's javascript. Is this possible?

Edit: Here is some code. I wrap my code in a function but where and how would you call this function?

function executeGlobJs() {
   alert("js reload success");
}
like image 605
beliy333 Avatar asked Nov 21 '22 15:11

beliy333


1 Answers

You could use the html5 history-api:

In your click-handler you'll call the pushState-method, stat stores the current state for later reuse:

$(document).on('click', 'a.link', function () {
  // some ajax magic here to load the page content
  // plus something that replaces the content...  

  // execute your custom javascript stuff that should be called again
  executeGlobJs()

  // replace the browser-url to the new url
  // maybe a link where the user has clicked
  history.pushState(data, title, url);
})

...later if the user browses back:

$(window).on('popstate', function () {
  // the user has navigated back,
  // load the content again (either via ajax or from an cache-object)
  // execute your custom stuff here...
  executeGlobJs()
})

This is a pretty simple example and of course not perfect! You should read more about it here:

  • https://css-tricks.com/using-the-html5-history-api/
  • https://developer.mozilla.org/en-US/docs/Web/API/History_API

For the ajax and DOM-related parts, you should need to learn a bit about jQuery http://api.jquery.com/jquery.ajax/. (It's all about the magic dollar sign)

Another option would be the hashchange-event, if you've to support older browsers...

like image 167
yckart Avatar answered Mar 11 '23 21:03

yckart