Should you use JavaScript to implement redirects? If you do use JavaScript to redirect pages, what is the best approach?
JavaScript redirects are problematic. This is because Googlebot only processes JavaScript redirects after crawling is completed. Server-side redirects are a much better option because they will be processed during a crawl. As a result, Google may not execute the JavaScript code and may not process the redirect on your website. Keep in mind that not all AI bots execute JavaScript and, therefore, would not process these redirects.
If your only option is to redirect via JavaScript, you want to make sure you implement the redirect as simply as possible in the code. You also want to place this code as high in the HTML as possible so that nothing else will interfere with the code being executed. It is also helpful to add the code directly to the page being redirected instead of embedding the JavaScript code to the redirected page from a separate file.
There are two different JavaScript methods you can use to implement a redirect. Both will work but there are some advantages and disadvantages to each method.
Method #1: window.location.href
Using window.location.href is similar to clicking a link using JavaScript code. It creates a new href to send visitors or robots to on your website. Google does appear to follow this method reliably.
Be careful, though, because this method can create a frustrating experience for users. That is because the page that redirects will be kept in the browser’s history. So if the user encounters this redirect then clicks the “back” button on their browser, they will return to the original page. In this case, that original page redirects, so users will be stuck in a loop unless they click the back button twice.
There is a way to do something similar with the code: window.location.assign(redirect_to_url); The difference is semantic. When you use window.location.assign(redirect_to_url), you’re specifically invoking a method to load a new document. When you use window.location.href = “redirect_to_url”, you’re changing the property of the window.location object, which implicitly loads a new document.
Code example:
redirect_to_url = "https://site.com/redirect-destination";
window.location.href = redirect_to_url;Method #2: window.location.replace()
The window.location.replace() method is the most similar to a server-side redirect and is typically the best method to use for JavaScript redirects.
If you use this method, the current page will not be kept in the browser’s history. If the user clicks the “back” button on their browser, they will not return to the original page but instead to whatever page was in the history before they loaded the original page.
Code example:
redirect_to_url = "https://site.com/redirect-destination";
window.location.replace(redirect_to_url);