Calling a javascript function after loading a page with window.location.assign

user823527 picture user823527 · Jul 8, 2011 · Viewed 8.5k times · Source

Is it possible to call a javascript function after loading a page with window.location.assign? I have this code.

<script language="javascript" type="text/javascript">
function Loadspirit(){
  window.location.assign("spirituality.php");
  ReadEnglish();
}
</script>

I load the page then call ReadEnglish(), a function defined in spirituality.php. The function doesn't execute. What would be the way to make the function execute?

Answer

jfriend00 picture jfriend00 · Jul 8, 2011

As soon as you assign a new window.location, the browser starts loading a new page in the current browser window. That stops execution of all javascript in this window and starts loading the new page. Only javascript in the new page will run from that point on. If you want a function after that new page is loaded, you will have to put that code in the new page. If want that function to run in the new page all the time, you can just set the code in that new page to always run that function when the page is loaded.

If you only want that new function to run in the new page when it's called from this particular context, then you need to pass some information to the new page and the code in the new page needs to look for that information to decide whether to run the ReadEnglish() function or not. The typical ways that you can pass information to the new page are

  1. Query parameters in the URL (items in the URL after the ? mark like "?run=English").
  2. Information set in a cookie
  3. Javascript variables in other windows/frames that are known to the new page and on the same origin.

Query parameters are often used if this is not a persistent setting, but rather an occasional execution of this option this particular time.

Cookies are often used if this is a more persistent setting because the cookie can persist until you tell it to go away.