How to redirect to another URL using a JavaScript redirect?
With a few lines of JavaScript code, you can redirect visitors to another URL. The recommended function is window.location.replace()
.
A little bit of background information: a JavaScript redirect is a client-side redirect that instructs browsers to load another URL.
Implementing JavaScript redirects
An example of what a JavaScript redirect to our homepage looks like:
<html> <head> <script> window.location.replace("https://www.conductor.com/"); </script> </head> </html>
This code would send a visitor to https://www.conductor.com/
upon page load.
The benefit of using the window.location.replace
function is that the current URL isn't added to the visitor's navigation history, whereas the popular JavaScript redirect window.location.href
would. That could cause a visitor to get stuck in back-button loops. Therefore, don't use it when redirecting visitors immediately to another URL.
<script> window.location.href='https://www.conductor.com/'; </script>
JavaScript redirects and SEO
From an SEO point of view it's not recommended to use JavaScript redirects because:
- Search engines are slow to pick up on them, because they need to render the page in order to find the redirect.
- There's no guarantee the redirect is picked up correctly, therefore it's unsure if you'll see the same amount of authority being passed on as you'd see with a 301 redirect.
- JavaScript redirects make for a slower user experience than for instance a 301 redirect.