5

My web application works on multiple handheld devices like iPads Galaxy tabs etc. Application request images from the server and render in on the Clients.

Now the problem is sometimes happens, that network connectivity is lost during the rendering of images, than that time that html no-image icon is shown on the devices...

I want to handle this situation gracefully, at the time of network loss , I want to capture that and show a alert to user that no network connectivity or something...

I tried to user navigator.onLine event.. but it is not working on all set of browser that I am support like, 5-6 version on mozilla etc.

And also my application will run only on wifi local network... May or may not be connected to internet.. will in that suitation also this navigator.onLine works..?

Please provide me any other better way to do this...

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Dhruv
  • 10,291
  • 18
  • 77
  • 126
  • In my entire experience as a coders, I have come to the conclusion that it is never possible to determine if you are online, independent of whatever platform or programming language – ControlAltDel Apr 20 '12 at 15:36

2 Answers2

2

For example, you can use

<img src="..." onerror="noConnection()">

So noConnection method will be called if an image was not loaded.

More info here: jQuery/JavaScript to replace broken images

Community
  • 1
  • 1
Eugene Retunsky
  • 13,009
  • 4
  • 52
  • 55
  • Could you add a link to the documentation? – Tadeck Apr 20 '12 at 15:37
  • 1
    Ok, maybe something more reliable than W3Schools? It would be great, as W3Schools is completely unreliable source of information. See here: http://w3fools.com/ – Tadeck Apr 20 '12 at 15:57
  • As far as it does refer to something more reliable than W3Schools ;) Eg. I prefer Mozilla Developer Network, but there are many other reliable sources. Ok, I think your answer is worth upvoting :) +1 – Tadeck Apr 20 '12 at 17:30
2

You could do a little XHR request to your server and check for the returned status.

If it is 0, this means the connection is missing.

So, something like this could give you a little utility function:

function isOnline ( callback ) {
    var xhr = new XMLHttpRequest( )
    xhr.onreadystatechange = function ( ) {
        // Make sure the request is finished
        if ( xhr.readyState === 4 ) {
            // There is the magic
            if ( xhr.status === 0 ) {
                callback( false )
            }
            else {
                callback( true )
            }
        }
    }
    xhr.open( '/some/url' )
    xhr.send( )
}

// Usage example:
isOnline( function ( status ) {
    if ( status ) {
        // You're online
    }
    else {
        // You're not online
    }
} )

PS: I skipped the IE-compliance part for the xhr object, but it'd be easy to add. This is more to get the idea.

Florian Margaine
  • 58,730
  • 15
  • 91
  • 116