Search code examples
htmlhrefwindow.location

What's the differences between window.location.href and <a href></a>?


I have just read some concept about window.location property and method. And I know that

1. window.location.href = "http://google.com"
2. window.location.assign("http://google.com")
3. window.location.replace("http://google.com")

are all can redirect our page to the target url, the only difference is that window.location.replace doesn't record the history, so we cannot get back to the previous page directly.

Now I just wondering, what's is the difference between window.location.href and <a href="http://google.com">Google</a>, the <a> tag also records the history. And for what situation do we use them respectively?


Solution

  • I think the main difference is what's happening behind the scene but on the surface they are pretty much giving the same effect.

    window.location.href is only triggerable by JavaScript, or in JS context. Whereas a <a> tag defines hyperlink in HTML. It really depends on how you want to trigger this new page. You can either have a hyperlink a user can click/tap on, or you can trigger the page load by some JS functions that are triggered by certain actions.

    To be more specific, a tag is common in webpages because browsers understand it and can apply CSS style to it to look nicer. As for window.location.href, there's no UI aspect for it, it simply is a line of JS code that you can trigger to either (1) get the current webpage URL or (2) set a value to it to redirect the user to some other URLs.