How to redirect to another URL using a JavaScript redirect?

Last updated: September 9, 2020

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.contentkingapp.com/");
		</script>
	</head>
</html>

This code would send a visitor to https://www.contentkingapp.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.contentkingapp.com/';
</script>

JavaScript redirects and SEO

From an SEO point of view it’s not recommended to use JavaScript redirects because:

  1. Search engines are slow to pick up on them, because they need to render the page in order to find the redirect.
  2. 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.
  3. JavaScript redirects make for a slower user experience than for instance a 301 redirect.
ContentKing Academy

Read the full Academy article to learn everything about Redirects

Start your free trial

Get up and running in 20 seconds

Please enter a valid domain name (www.example.com).
  • No credit card required
  • No installation needed
  • No strings attached