JavaScript Redirect

To perform a client-sided redirect with JavaScript we can use the window.location object. Learn more in this tutorial.

1309 views

Edited: 2019-09-11 16:05

To make a JavaScript Redirect you need to use the window.location object, this is done by simply feeding it with the URL that you want to redirect to. But there are more to redirects then what can be seen on the client side, the important part is often the part happening on the server – those seeking to use JavaScript for redirects, should note that you can not send header responses with JavaScript, so your redirect may not have the desired effect for search engines.

The window.location object can be used whenever you want to send a client sided redirect, this will often strictly be done when you can not use server-sided scripting. The below code can be placed in your head section.

window.location="http://beamtic.com/";

And as a reminder, here is the full code, ready to be pasted in the head section of your HTML.

<script type="text/javascript">
window.location="http://beamtic.com/";
</script>

The Disadvantages of a JavaScript Redirect

The JavaScript redirect is considered dirty in most situations – there likely are times where it would be fine and very suitable – but the majority of web developers likely never encounter them. If you can't see a reason to use it, then you likely shouldn't be using it – the best advice is to stick with server-sided redirects unless you really need to use JavaScript.

JavaScript based redirects will not pass PageRank, and it will most likely not have the desired effect in search engines. Search engines look at the header response of the requested resource, and the header response is delivered from the server-side.

It is considered safer to rely on server-sided redirects for now – if you for some reason can not use server-sided redirects, you may want to consider using a meta refresh redirect instead.

See also

  1. Redirecting pages with htaccess
  2. Meta Tag Redirects
  3. Canonical Tag

Tell us what you think:

  1. An in-dept look at the use of headings (h1-h6) and sections in HTML pages.
  2. Pagination can be a confusing thing to get right both practically and programmatically. I have put a lot of thought into this subject, and here I am giving you a few of the ideas I have been working with.
  3. The best way to deal with a trailing question mark is probably just to make it a bad request, because it is a very odd thing to find in a request URL.
  4. How to optimize image-loading and automatically include width and height attributes on img elements with PHP.
  5. HTTP headers are not case-sensitive, so we are free to convert them to all-lowercase in our applications.

More in: Web development