How to Redirect to Another Web Page Using JavaScript?

In this article we'll look at different ways we can use to redirect to a new web page (or a resource) using only JavaScript. In addition to that we'll also be exploring the potential fallbacks you can put in place when JavaScript is disabled, the SEO impact of using JavaScript for redirection purposes and alternative solutions.

#Redirect Using JavaScript

Ideally, a redirect should be issued from the backend with correct HTTP redirect headers sent to the client. But if we must redirect from JavaScript, we can do so using the methods below:

// redirect to a new page
window.location.href = 'https://www.example.com/';

// same as window.location.href = ...
window.location = 'https://www.example.com/';
window.location.assign('https://www.example.com/');

// redirect to new page and,
// replace the original document in browser history with new one
window.location.replace('https://www.example.com/');

In most cases, the replace() function might be the best option as it won't cause redirect loops when users hit the browser's back button.

Some browsers and most web crawlers may not execute JavaScript for various reasons, which is why having a fallback in place is a good idea.

Fallback When/If JavaScript Is Disabled:

Preferably, we should issue HTTP headers originating from the backend (server-side) to issue a redirect with appropriate redirection code. However, since we're specifically talking about JavaScript / Frontend redirection, we could use HTML's meta tag refresh (in the <head></head> section of the web page) to instruct the browser to refresh the current web page (or an iframe) after a specified time interval (in seconds). Consider the following example:

<meta http-equiv="refresh" content="0; url=https://example.com/" />

The 0 specified in the content attribute instructs the browser to redirect immediately. Changing it to a positive non-zero value would instruct the browser to wait before refreshing the page (the value is interpreted in seconds).

Additionally, we can place a fallback, for example a link, for older browsers in case the meta refresh doesn't work:

<p>
    <a href="https://example.com/">Redirect</a>
</p>

To make sure, the code only executes when/if the browser has JavaScript disabled, we could wrap the meta tag (or other relevant code) inside a noscript tag like so:

<noscript>
    <meta http-equiv="refresh" content="0; url=https://example.com/" />
</noscript>

Potential Side-Effects:

  • If a page redirects too quickly (i.e. in less than 2-3 seconds), it can break the Back button on the browser as each time you move back to the redirecting page, redirection will occur again almost immediately. This is especially bad in terms of usability as it can trap the user on the page he was redirected to.
  • It can be considered as a "Doorway Page" which is considered as an un-ethical SEO process by search engines.
  • Sometimes a mistake, or poorly planned redirections, can cause an infinite sequence of redirects, redirecting back and forth between two or more pages.

JavaScript Redirect's Impact on SEO:

Why a JavaScript Redirect May Impact Your Search Engine Ranking Negatively:

Like mentioned previously, most web crawlers may not execute JavaScript which may negatively impact your web page's search engine ranking. You might imagine using meta refresh would resolve the issue for all web crawlers, but such is not the case. In fact, an HTML page that contains a meta refresh element returns an HTTP status code of 200 OK (which is different from redirect status codes such as 301, 302, etc.). How that HTML 200 OK response (with a meta refresh tag) is processed and/or interpreted by a user-agent/bot/crawler depends entirely on the agent, its specific purpose and its programming.

Alternatives to JavaScript Redirect, Without Compromising SEO:

The best way to overcome these issues may be:

  1. To add a link rel=canonical in the <head></head> section of your web page to inform search engines of a duplicate page (e.g. <link rel="canonical" href="https://www.example.com/" />); this is easier to implement as it doesn't involve doing anything on the server-side. However, you must keep in mind that all search engines or web crawlers may not honor it;
  2. To issue either of the following HTTP headers from the web server (or a backend/server-side script):
    1. To properly issue an HTTP redirect header with most-appropriate redirect status code such as 301, 302, etc., or;
    2. To display a 404 Not Found for web pages that you may want to kill off and let die.

Although a 404 may be considered bad for SEO in most cases, it may still be more meaningful in some. To help determine what course of action may be best suited in your particular case, you might want to ask yourself the following:

  1. Does the page receive important links to it from external sources?
  2. Does the page receive a considerable amount of visitor traffic?
  3. Is it an obvious (or a popular) URL that visitors/links intended to reach?

If answer to any of those is a yes, you might want to consider a 3xx redirect instead of a 404. Otherwise, it may be alright to issue a 404 – the reason being 1) we'd save up bandwidth from search engines trying to crawl and index a junk/stale page, and 2) we'd be able to inform the user about the error and display a search option and/or other relevant links instead (which may enhance the user experience).

#Redirect Immediately After Page Load

By simply placing the redirect code in the <head></head> section of the webpage (wrapped in script tag of course) we can issue an immediate redirect. For example:

window.location.href = "https://www.example.com";

Or, as an alternative, we could also use an inline onload event on the body tag like so:

<body onload="window.location = 'https://example.com/'">

    <!-- Your content here -->

</body>

In this case, however, you must note that everything that preceedes the body tag will be parsed by the browser first.

Redirect When Web Page Loads:

If you wish to make sure the web page finishes loading, or certain scripts etc. load before issuing a redirect, depending on exactly when you intend to do it, you may benefit from the following three events in this particular case:

  1. window.onload Event: fired when DOM is ready and all the contents including images, css, scripts, sub-frames, etc. finished loaded (i.e. everything is loaded).
  2. document.onload Event: fired when DOM tree (built from markup code within the document) is ready, which can be prior to images and other external content is loaded.
  3. document.onreadystatechange Event: fired when:
    1. the document is still loading;
    2. document finished loading with resources (such as images, css, frames, etc.) still pending;
    3. document and all sub-resources have finished loading (i.e. window.onload is about to fire).

Examples:

// Example #1
window.addEventListener('load', function(event) {
    // all resources finished loading
    window.location = 'https://www.example.com/';
});
// Example #2
document.onreadystatechange = function () {
    switch(document.readyState) {
        case 'loading':
            // document still loading
        break;
		
        case 'interactive':
            // document has finished loading; DOM elements can now be accessed
        break;
		
        case 'complete':
            // page is fully loaded (i.e. all resources finished loading)
        break;
    }
}

#Redirect After a Certain Period of Time Has Elapsed

To delay the redirect by a few seconds, we can use JavaScript's setTimeout function like so:

// redirect in 3 seconds (or 3000 ms)
setTimeout(function() {
    window.location.href = "https://www.example.com";
}, 3000);
  • Time in setTimeout function is defined in miliseconds (i.e. 1000 ms = 1 second).
  • Since a web page is parsed sequentially from top to bottom, script tags (that are not marked defer or async) load and execute before the parsing of the rest of the page continues. Therefore, placing the code in the <head></head> section of the web page should execute the code immediately and redirect in the specified number of miliseconds. You could, however, also place this code at the end of the web page (or anywhere in the page for that matter), which would mean the code will execute when the browser parser reaches the particular segment of the code in the document.

This post was published (and was last revised ) by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.