What's the difference between window.location= and window.location.replace()?

Viewed 365534

Is there a difference between these two lines?

var url = "http://www.google.com/";
window.location = url;
window.location.replace(url);
3 Answers

Origins & a Solution

The Question

Is there a difference between these two lines?
window.location = "http://www.google.com/";
window.location.replace("http://www.google.com/");

Short Answer

Yes.

Background Facts

First, you want to know that:

window.location = "https://stackoverflow.com" is an alias of window.location.href = "https://stackoverflow.com" thus has the same functionality.

window.location VS window.location.replace

window.location:

Here, I am addressing window.location = "https://website.com" in its context as window.location.href = "https://website.com"

  • The href property on the location object stores the URL of the current webpage.
  • On changing the href property, a user will be navigated to a new URL.
  • This adds an item to the history list
  • after moving to the next page, the user can click the "Back" button in the browser to return to this page.

window.location.replace:

  • The replace function is used to navigate to a new URL without adding a record to the history.
  • This function is overwriting the topmost entry and replaces it from the history stack.
  • By clicking the "Back" button, you will not be able to return to the last page you visited before the redirect after moving to the next page.

Conclusion:

To answer the question:

Yes, there is a difference between our 2 subjects and mostly in the fact that window.location enables you to go back in the browser history while window.location.replace() doesn't let you go back in browser history, thus removing the previous URL record from the browser history.

Bonus: Which is faster?

When you are using this: window.location = "http://www.google.com/"; you are updating the href property directly, this is faster by performance than using window.location.replace("http://www.google.com/"); because updating a function is slower than updating a property directly.

More about window.location

window.location returns the Location object that looks like this inside:

console.log(window.location);

// This is how the Location object that returns from window.location looks like
{
    "ancestorOrigins": {},
    "href": "https://stackoverflow.com/",
    "origin": "https://stackoverflow.com",
    "protocol": "https:",
    "host": "stackoverflow.com",
    "hostname": "stackoverflow.com",
    "port": "",
    "pathname": "/",
    "search": "",
    "hash": ""
}

The Location object also has the following methods (functions):

Location.assign()
Loads the resource at the URL provided in parameter.

Location.reload()
Reloads the current URL, like the Refresh button.

Location.toString()
Returns a String containing the whole URL. It is a synonym for Location.href, though, it can't be used to modify the value.

Related