Search This Blog

Wednesday, May 14, 2008

Javascript Redirect Scripts

Redirecting a visitor with javascript is pretty straightforward. The simplest way is to use one of the methods below.
Note that in some cases a server-side redirect (i.e. one using a language such as PHP, ASP or Perl) is a better choice, since not all users will have javascript enabled. Search engine spiders are unlikely to follow javascript based redirects. <span style="font-weight:bold;">Location.href Method</span> <script type="text/javascript"> window.location.href="http://www.example.com/"; </script> Including this script on a page will immediately redirect visitors to the URL entered. Location.replace Method The difference between location.href and location.replace is that the former will create a new history entry on the visitors computer. This means that if they hit the back button, they can get stuck in a 'redirection loop'. This is usually undesirable and may have unwanted side effects - most pay per click search engines will not allow the submission of URLs that 'break' the back button. The solution is to use location.replace instead: <script type="text/javascript"> location.replace('http://www.example.com/'); </script> Conditional Redirects with Javascript Once you know how to redirect visitors, you can send them to different pages based on a variety of criteria. The example script below will redirect visitors with a resolution of 1024x768 or higher to a different page. Of course, there shouldn't be any reason to do so for most websites, which should work at any screen resolution ;) <script language="JavaScript" type="text/javascript"> if ((screen.width>=1024) && (screen.height>=768)) { window.location.replace('example.html'); } </script> <script language="JavaScript" type="text/javascript"><br />if ((screen.width>=1024) && (screen.height>=768))<br />{<br /> window.location.replace('example.html');<br />}<br /><br /></script>

No comments: