Re-execute js on the back without reloading the entire page

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

Tell me if I have a parent page and an inner page. When the called inner page is called, it is called via ajax, replacing the contents of the parent page. When the user clicks back, I would like to return to the parent page without reloading the page. But, the user interface of the parent page relies on javascript, so after they return, I would like to re-execute the parent javascript page. Is it possible?

Edit: Here is the code. I am transferring my code to a function, but where and how could you name this function?

function executeGlobJs() {
   alert("js reload success");
}
+4
source share
4 answers

You can use html5 history-api:

In your click-handler you call the method pushState, stat saves 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 views:

$(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 certainly not perfect! You should read about it here:

For parts related to ajax and the DOM, you need to learn a little about jQuery http://api.jquery.com/jquery.ajax/ . (All about the magic dollar sign)

hashchange -event, ...

+1

javascript . javascript .

, concat (, Gulp)

0

script, , .

script -, @s4n989, @Rudolf Manusadzhyan . , .

0

,

.preventDefault();

, , - https://api.jquery.com/event.preventdefault/

, !


EDIT:

By the way, if you want to execute JS on the back, you can wrap the script inside

$('.your-div').on('load', function(e) {
    e.preventDefault();
    //your JavaScript goes here
}
-1
source

Source: https://habr.com/ru/post/1628438/


All Articles