Little help in this simple script!

Discussion in 'JavaScript' started by luckmann, May 17, 2011.

  1. #1
    This script basically lets users on my forum to know if the Download Server is Online or Offline...

    But the problem is, when the server is unreachable the script take long time to get the error, therefore the offline images appears after 60 secs if not more...
    How can i make this script fetch the offline image after 5 secs and not wait long time

    in other words:

    Get image online.gif from download.server.com if not reachable in 5 sec go to other.server.com and get offline.gif


    Here is the script i am using now

    <script>
    var time = (new Date()).getTime();
    document.write('<img class="status" src="http://downloads.myserver.com/onlineimage.gif?'+time+'" alt="" onerror="this.src=\'http://downloads.anotherserver.com/offlineimage.gif\';" />');
    </script>
    Code (markup):
    Thank you
     
    luckmann, May 17, 2011 IP
  2. Cash Nebula

    Cash Nebula Peon

    Messages:
    1,197
    Likes Received:
    67
    Best Answers:
    0
    Trophy Points:
    0
    #2
    You could use a timer to call a function that tests with width of the online image.
    If it's zero because the server is offline, the function will load the offline image.

    The red lines were added to stop the spinning loading icon. You can remove them if they cause problems.

    
    <html>
    <head>
    <script type="text/javascript">
    	var img = new Image();
    	window.onload = function() {
    		img.src = 'http://downloads.myserver.com/onlineimage.gif';
    		setTimeout('serverStatus()', 5000);
    	}
    	function serverStatus() {
    		if (img.width != 0)	{
    			var time = (new Date()).getTime();
    			document.write('<img class="status" src="http://downloads.myserver.com/onlineimage.gif?' + time + '" alt="" />');
    		} else {
    			document.write('<img class="status" src="http://downloads.anotherserver.com/offlineimage.gif" alt="" />');
    		}
    [COLOR="red"]		if (window.stop !== undefined) window.stop();
    		else if (document.execCommand !== undefined) document.execCommand("Stop", false);[/COLOR]
    	}
    </script>
    </head>
    <body>
    </body>
    </html>
    
    Code (markup):
     
    Cash Nebula, May 17, 2011 IP