0

I've found 5 different ways to change current location on a webpage. Which one's better and way are they all needed?

This is basically what I found:

window.location.assign("www.example.com")

does the same as

window.replace("www.example.com")

the difference is that replace() removes the URL of the current document from the document history, meaning that it is not possible to use the "back" button to navigate back to the original document.

But what's the difference between these two and changing the location by

window.location = "www.example.com" ?

What about

<a href> ?

And

history.pushState?

EDIT

Some of you marked this as duplicated because of Javascript: Setting location.href versus location and What's the difference between window.location= and window.location.replace()? but it is not. My question's far wider than this.

It's everywhere "how to change location" but I didn't find a full comparison between these methods.

0

1 Answer 1

2

window.location adds an item to your history in that you can (or should be able to) click "Back" and go back to the current page.

assign(url): Load the document at the provided URL.

replace(url): Replace the current document with the one at the provided URL. The difference from the assign() method is that after using replace() the current page will not be saved in session history, meaning the user won't be able to use the Back button to navigate to it.

2
  • Thank you, and what about history.pushState? Which one should I use if I don't care whether they can navigate back or not?
    – Ssr1369
    Commented Feb 17, 2015 at 17:33
  • Use window.location. Why to trouble the user.
    – void
    Commented Feb 17, 2015 at 17:39

Not the answer you're looking for? Browse other questions tagged or ask your own question.