views:

962

answers:

4

How do you check if there is an internet connection using Javascript? That way I could have some conditionals saying "use the google cached version of JQuery during production, use either that or a local version during development, depending on the internet connection".

+1  A: 

You can try by sending XHR Requests a few times, and then if you get errors it means there's a problem with the internet connection.

Edit: I found this JQuery script which is doing what you are asking for, I didn't test it though.

Soufiane Hassou
This doesn't work. He needs to check if the network is there BEFORE getting jQuery, SO THAT HE CAN GET JQUERY.
Mike Trpcic
if he is in the page, then he already got JQuery ... am I missing something ?
Soufiane Hassou
Re-read his question. He needs to test the connection BEFORE the page load. If there IS a connection, he wants to get the Google hosted jQuery. If there ISN'T a connection, then he wants to get the local jQuery. This must all be done BEFORE loading jQuery, as the entire process serves the purpose of loading jQuery.
Mike Trpcic
Good point about JQuery, though, the XHR solution is valid.
Soufiane Hassou
As I commented elsewhere in my thread, the XHR stuff has too many points of failure to be reliable. Slow server, busy server, lagging connection, etc. can all result in a failed XHR.
Mike Trpcic
A: 

edit: this solution is only for subsequent calls when the page is already loaded and we need to detect if we still have internet access. that's how i interpreted the first version of the question. navigator.online is more elegant for the 'first-time-check' though.

google should have a good uptime for this test :-)

the first function is an event handler which is only being called, when the get-function will not succeed. the callback of the get-function will only be called on success.

$('body').ajaxError(function() {
  alert("failed");
});

$.get('http://www.google.de', function(data) {
  alert("success");
});
henchman
This won't work if he can't load jQuery first, which is his problem.
Mike Trpcic
you don't have to get jquery via CDN, but can put it on your server... then this will work :-)
henchman
He's checking the network FIRST because he WANTS to use the Google CDN. If there's no network connection, THEN load the local one. Your solution is completely bypassing his problem.
Mike Trpcic
i get your point. your solution is also using google CDN to be able to use the google API. both FAILED :/
henchman
Google != "internet", however the lines are blurred.
Joseph Silvashy
constructive criticism is always showing up alternatives to bad examples... otherwise, i fully agree with you (remember a day where google had downtime and everybody was like: uhhh, internet is broken... via instand messaging -_-)
henchman
A: 

Sending XHR requests is bad because it could fail if that particular server is down. Instead, use googles API library to load their cached version(s) of jQuery.

You can use googles API to perform a callback after loading jQuery, and this will check if jQuery was loaded successfully. Something like the code below should work:

<script type="text/javascript">
    google.load("jquery");

    // Call this function when the page has been loaded
    function test_connection() {
        if($){
            //jQuery WAS loaded.
        } else {
            //jQuery failed to load.  Grab the local copy.
        }
    }
    google.setOnLoadCallback(test_connection);
</script>

The google API documentation can be found here.

Mike Trpcic
well, you can check if google is up/down :-)
henchman
Why do something like that, if the google API will do it in a cleaner, more readable, programmatic way?
Mike Trpcic
for using the google api you also need a js-file. you can only use this with an api key provied by google - it's not a good idea of putting it on your own server, because if the api changes, your code will not work anymore...
henchman
The API won't change. Google is battle tested, and are the most reliable provider out there. NOT using the method above is just folly.
Mike Trpcic
mike your check only works once, when the page is loaded. in a real world scenario, you would want to check for internet connection more than only once... thats why your HAVE TO use xhttpr
henchman
Why would you want to check more than once? Once you know it's there, you go grab jQuery and you no longer need to check, since you've got the file you were looking for.
Mike Trpcic
+2  A: 

You could try:

var online = navigator.onLine;

Read more about the W3C's spec on offline web apps, however be aware that this will work best in modern web browsers, doing so with older web browser's may be pretty tough.

Alternatively an XHR request to your own server isn't that bad method for testing your connectivity. Consider one of the other answers state that there are too many points of failure for an XHR, but if your XHR is flawed when establishing it's connection than it'd also be flawed during routine use anyhow.

Therefore it's a suitable fallback from navigator.onLine.

It would be a really bad idea to make an XHR request to someone else's server, even google.com for that matter. Make the request to your server, or not at all.

The best option in your case might be:

In your html <head> tag

<script type="text/javascript" src="http://www.google.com/jsapi"&gt;&lt;/script&gt;
<script id="jquery_loader"></script>

In your js file (or possibly still in the <head> if you want):

function loadJQuery() {
  if (navigator.onLine(connected)) {
    google.load("jquery", "1.4.1");
  } else {
    document.getElementById('jquery_loader').src = '/javascripts/jquery.js';
  }
 }

Then right before your close </body> tag:

<script>
  loadJQuery();
</script>

Bizarrely enough, the reason this works is because writing to the objects attributes calls the browsers parsing engine again, which will have to parse the script tag and thus include the local file if the browser is deemed offline by the prior method.

You might say, why put the script tag at the end of the <body>? This is because without jQuery's ready() function, we are stuck to emulate the readiness of the DOM, and this would be the best way to do that, the only native option would be the onload attribute of your body tag, but this happens far later in load sequence of your page (just after the reflow and draw).

I basically just explained how browsers work for no reason.

[sighs]

Joseph Silvashy
`navigator.onLine`, last time I checked, is available on for IE browsers, so for those browsers not supporting `navigator.onLine`, using XHR request as you have mentioned.
The Elite Gentleman
Nope, it is available in firefox: https://developer.mozilla.org/En/DOM/Window.navigator.onLine
Joseph Silvashy
It's also available for Safari/WebKit/Chrome and Opera. But it should be pointed out that it does not check that you have an Internet connection - only that you are connected to a network. It is a very cheap and dirty test.
DavidG