Detecting connection loss

Hi all,

I have a script which needs to detect when the internet connection is lost and hold the content of the web page until the connection is restored.

I have been given a head start with a small javascript which I am trying to get to work.

My web page, I have a web page which contains some text and graphics but more importantly it also has an iFrame. The iFrame connects to an SQL database and displays data which is refreshed every 20 seconds. Because the internet connection at the location where the script will be running I get connection loss which makes the iFrame loose its data. The Javascript I am working with is below, can anyone see why it should not work and give a hand in solving the problem.


var hasConnectionBeenLost = false;
(function ( img, wait, notify )
{
    var iObj = new Image();

    iObj.onerror = function ()
    {
        if ( notify )
    {
            alert( 'reloading' );
            hasConnectionBeenLost = true;
            setTimeout( test, wait );
            //display some message to user connection is lost
            //document.getElementById("someElementMessage").style.display="block";
        }

        iObj.onload = function ()
        {
            if (hasConnectionBeenLost)
            {
                location.reload( true );
            } 
    		else 
    		{
                setTimeout( test, wait );
            }
        };

 

        function test()
   			{
            iObj.src = img + '?t=' + new Date();
     	   }

        test();

    }( 'images/myimage.gif', 80000, false );
}
);

Many thanks in advance.

Best regards,

Bytec

Just as an aside, there are a few other methods to this sort of thing as well, I found a post on StackOverflow that describes a few methods and there is even a tiny [URL=“http://jamiethompson.co.uk/web/2008/06/17/publish-subscribe-with-jquery/”]jQuery plugin to do this.

As far as your code is concerned, you seem to be using a JavaScript closure that’s not executing itself at the end…

Try moving the “( ‘images/myimage.gif’, 80000, false )” to the last line, as per below:

var hasConnectionBeenLost = false;
(function ( img, wait, notify )
{
    var iObj = new Image();
    iObj.onerror = function ()
    {
        if ( notify )
    {
            alert( 'reloading' );
            hasConnectionBeenLost = true;
            setTimeout( test, wait );
            //display some message to user connection is lost
            //document.getElementById("someElementMessage").style.display="block";
        }

        iObj.onload = function ()
        {
            if (hasConnectionBeenLost)
            {
                location.reload( true );
            } 
    		else 
    		{
                setTimeout( test, wait );
            }
        };

 

        function test()
   			{
            iObj.src = img + '?t=' + new Date();
     	   }

        test();

    }
}
//make sure the closure executes
)( 'images/myimage.gif', 80000, false );