Home & blog  /  2010  /  Aug  /  view post  /

How to: detect internet connection in Javascript

posted: 18 Aug '10 13:54 tags: how to, connection, offline, image

I am working on a project currently that involves content being delivered for offline use, with no certainy an internet connection will be present.

There's a feedback form, and since forms need a PHP (or other) handler to receive and process the post data, the form was to be available only if a connection was present and the handler could be loaded.

Which led me innevitably to the question: how to check for an internet connection in JS?

AJAX springs to mind, but there's the Same Origin Policy just waiting to trip you up on that one. Yes, you could have your AJAX request call a PHP script which, through something like cURL(), can check for a remote connection, but not if you don't have PHP in the environment.

Eventually I opted on a very simple technqiue, but which appears safe: run a native, DOM-zero onload event on a remote image.

The obvious - and only - risk here is that if the site hosting the image was down, your JS script would think there was no internet connection.

So load an image on the site whose remote assets you need to call (in my case, the PHP handler). If that's down, then it amounts to the same thing as there being no internet connection, as either way your handler won't be loaded.

Here's the code involved:

1var img = document.createElement('img');

2img.src = "http://www.somesite.com/myimage.jpg";

3var connection = false;

4img.onload = function() { connection = true; }

You can subsequently check for a connection by querying the boolean connection.

That's fine if your code is in a function and invoked by an event some time after load, but if it's JS that's set to run automatically, you'll need to delay it a few seconds at least to make sure the image load request has had chance to run.

In which case, put your code in a setTimeout() callback, e.g.

1setTimeout(function() {

2     /* your code here

3     ...

4     etc */

5}, 3000); //your code waits 3 seconds then runs

post new comment

Comments (3)

Chuks, at 12/12/'11 00:18, said:
Please how do i use this script. I need to apply this somewhere in an app i am working on. The app is based on php technology. Thank you in advance.
Mitya, at 12/12/'11 16:05, said:
If you're using PHP it would make sense for testing internet connection there, not in JS. This is fairly simply - just make any request for content to a remote resource, and if it comes back, you have a connection. Look at file_get_contents() or the cURL library (pre-installed on most PHP builds).
philp kauffman, at 14/08/'12 04:24, said:
Good idea about the image. But... what if the image is in the browser's cache? Wouldn't the onload event fire when the browser loads the image from cache?