How to redirect to another URL using a JavaScript redirect?

Last updated: June 20, 2021

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>
Are JavaScript redirects hurting your SEO performance?

Check your website for excessive redirects, and incorrect configurations right now!

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.

Keep learning: check out our JavaScript SEO Beginner's Guide!

Read the full Academy article to learn everything about Redirects