Forum Moderators: open

Message Too Old, No Replies

Javascript If/Else Redirect Script

Script checks in with a central server, but has a contingency plan

         

aeae

9:15 pm on Sep 28, 2007 (gmt 0)

10+ Year Member



Hello,

I'm creating a simple html page which basically consists of a javascript redirect. (Yes, I know there are benifits of other redirects, but this needs to be a javascript redirect.)

What I need to do is for the script to check with a central server to see where the user should be redirected. However, if the central server is down, or no longer exists, the user would redirect to a default location.

How I did this was to create a variable "redirect", and set this to FALSE. Then I have the script request a script from the central server. On the script provided also exists a variable called "redirect", but this time set TRUE, as well as a variable called "url" set to "http://www.site1.com/".

The third part of the original script would have an if/else statment. If redirect is TRUE, redirect the user to what url equals, else, use the default setting.

I'm curious if this is the most efficint and best way to set this up. I do have the third part of the script set to defer, if that makes any difference.

Your opinions and feedback are much appreciated. Thanks.

The script is below

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Redirect</title>
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
<script type="text/javascript">var redirect=false;</script>
<script src="http://www.domain.com/request.js"></script>
<script type="text/javascript" defer="defer">
if(redirect==true) external.menuArguments.location.href=url;
else external.menuArguments.location.href="http://www.site2.com/";
</script>
</head>
<body>
</body>
</html>

penders

5:35 pm on Sep 29, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Hi aeae, I recently did something similar but different in that I checked for the existence of a remote image and in the onload event of the image I redirected to the external URL (fixed), otherwise it 'timed out' after a few seconds and did a META direct to a 'local version'. It would ultimately redirect to the 'local version' if JS was disabled - but that really wasn't an issue in this case anyway.

I think I prefer your method. Presumably it has been working OK? Just a couple of points. I think you can avoid having to initialise your redirect variable.

var redirect=false;

And then you can simply test:

if (redirect!= undefined) ...

Is the

defer
attribute required? I believe this is supported by IE4+, but AFAIK FF1.5 and Op8 do not support this attribute?

At first I thought you might get an error if the external script didn't exist (ie. the server wasn't available) - but this doesn't seem to be the case.