Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does changing window.location stop execution of javascript?

Tags:

javascript

When writing server-side code you need to explicitly stop execution after sending a "Location: ..." header to the client or your code will continue to execute in the background.

But what about when you change window.location in a client-side script? Does this immediately stop execution of the current script or is it up to the programmer to make sure that any code located after this call is not reached?

like image 661
Aleksander Kmetec Avatar asked Mar 29 '10 09:03

Aleksander Kmetec


People also ask

What is the use of window location in JavaScript?

The window. location object can be used to get the current page address (URL) and to redirect the browser to a new page.

What's the difference between window location and document location in JavaScript?

The window. location is read/write on all compliant browsers. The document. location is read-only in Internet Explorer but read/write in Firefox, SeaMonkey that are Gecko-based browsers.

Which method is used to stop the JavaScript or temporary?

Window stop() The stop() method is the same as clicking stop in the browser.


2 Answers

Setting window.location does not implicitly stop JS execution. Take the following as an example:

function locationTest() {
  window.location = 'http://www.google.com/';
  window.open('http://www.yahoo.com/');
}

locationTest();

Try running that from Firebug/Web Inspector/etc. and you'll notice that the current window will load Google, but a new window will open with Yahoo as well.

like image 27
Jimmy Avatar answered Oct 05 '22 04:10

Jimmy


Does this immediately stop execution of the current script

No, the remaining handler script will execute to the end before control returns to the browser and events start happening. When loading of the new page gets far enough for ‘navigation’ to occur, the beforeunload and unload events will fire, then the page and any script in it will become inactive.

However, any further queued events and timeouts might not fire. For example if you navigate the page in a click handler of a form submit button and don't cancel the default action, it is possible (race condition) for the navigation to occur before the submit event queued by the default action of the click.

like image 173
bobince Avatar answered Oct 05 '22 04:10

bobince