Changing the current page subtleties

04 Mar 2011 by David Corvoysier

The window.location object has two methods to tell the browser to navigate to a new URL: replace and assign. The only difference between the two methods is that window.location.replace will not insert a new page in the history: as a consequence, the user will not be able to return to the original page using the back button of the browser.

In all automatic redirection use cases, using window.location.replace makes sense, as the web developer probably doesn't want the user to be able to come back to the original page, but there are several other use cases where window.location.assign makes more sense, because you actually want the user to be able to use the back button.

So, you would expect both methods to be equally popular, right ? Wrong !

Google search on window.location.replace -> more than 47 millions responses ...

Google search on window.location.assign -> only 280 000 responses !

Okay, maybe that's because window.location.assign("url") is equivalent to window.location.href="url". Well, not only ...

Google search on window.location.href -> "only" 12 millions responses ...

So, I am now wondering whether people use window.location.replace because it is what they need or just because it comes out first when they google for a way to change a page using javascript ...

comments powered by Disqus