222

How do you check if there is an internet connection using jQuery? 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".

10
  • 5
    How does the javascript get downloaded to the browser?
    – S.Lott
    Commented Mar 5, 2010 at 2:36
  • 2
    sometimes I go to cafes and places in the middle of nowhere and they don't have decent/any internet, so I'd want to automate getting around that problem once and for all :). for testing/side projects.
    – Lance
    Commented Mar 5, 2010 at 7:21
  • 7
    I'm not sure what @viatropos goal is here, but I see testing the connection with javascript as a valuable way of making web apps that work offline, consider an application like gmail, wouldn't it be great if it utilized client side storage so that you can compose messages and still use the app in a limited way, then when the browser has it's connection again it can send and receive again. Commented Mar 5, 2010 at 20:06
  • 1
    How does a Javascript app work "offline"? Where does the javascript come from? I'm still unable to figure out what the use case is. Could you provide a more complete scenario showing where the javascript comes from?
    – S.Lott
    Commented Mar 6, 2010 at 6:02
  • 3
    @S.Lott Javascripts can be used to build html executable files (appjs, tidesdk, nodejs), or the html files could be a local web-app, therefore, there could be a need for checking internet connections Commented Feb 6, 2014 at 5:41

9 Answers 9

270

The best option for your specific case might be:

Right before your close </body> tag:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.10.2.min.js"><\/script>')</script>

This is probably the easiest way given that your issue is centered around jQuery.

If you wanted a more robust solution 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 browsers may not work as expected, or at all.

Alternatively, an XHR request to your own server isn't that bad of a method for testing your connectivity. Considering one of the other answers state that there are too many points of failure for an XHR, if your XHR is flawed when establishing it's connection then it'll also be flawed during routine use anyhow. If your site is unreachable for any reason, then your other services running on the same servers will likely be unreachable also. That decision is up to you.

I wouldn't recommend making an XHR request to someone else's service, even google.com for that matter. Make the request to your server, or not at all.

What does it mean to be "online"?

There seems to be some confusion around what being "online" means. Consider that the internet is a bunch of networks, however sometimes you're on a VPN, without access to the internet "at-large" or the world wide web. Often companies have their own networks which have limited connectivity to other external networks, therefore you could be considered "online". Being online only entails that you are connected to a network, not the availability nor reachability of the services you are trying to connect to.

To determine if a host is reachable from your network, you could do this:

function hostReachable() {

  // Handle IE and more capable browsers
  var xhr = new ( window.ActiveXObject || XMLHttpRequest )( "Microsoft.XMLHTTP" );

  // Open new request as a HEAD to the root hostname with a random param to bust the cache
  xhr.open( "HEAD", "//" + window.location.hostname + "/?rand=" + Math.floor((1 + Math.random()) * 0x10000), false );

  // Issue request and handle response
  try {
    xhr.send();
    return ( xhr.status >= 200 && (xhr.status < 300 || xhr.status === 304) );
  } catch (error) {
    return false;
  }

}

You can also find the Gist for that here: https://gist.github.com/jpsilvashy/5725579

Details on local implementation

Some people have commented, "I'm always being returned false". That's because you're probably testing it out on your local server. Whatever server you're making the request to, you'll need to be able to respond to the HEAD request, that of course can be changed to a GET if you want.

20
  • 1
    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. Commented Mar 11, 2010 at 21:36
  • 2
    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
    Commented Oct 25, 2010 at 13:18
  • 8
    problem was that the different browser developers couldn't decide what "online" means
    – Thariama
    Commented Oct 26, 2011 at 12:42
  • 6
    navigator.onLine is very unreliable, if you have a virtual network adapter such as kerioVPN you need to disconnect that virtual adapter and all the other network adapters to change navigator.onLine to false Commented Apr 27, 2014 at 8:13
  • 2
    var online = navigator.onLine;. its a really nice solution for firefox cache issues. If you dont want your html pages to be cached and displayed while firefox is offline, use this. Commented Mar 11, 2016 at 5:06
42

Ok, maybe a bit late in the game but what about checking with an online image? I mean, the OP needs to know if he needs to grab the Google CMD or the local JQ copy, but that doesn't mean the browser can't read Javascript no matter what, right?

<script>
function doConnectFunction() {
// Grab the GOOGLE CMD
}
function doNotConnectFunction() {
// Grab the LOCAL JQ
}

var i = new Image();
i.onload = doConnectFunction;
i.onerror = doNotConnectFunction;
// CHANGE IMAGE URL TO ANY IMAGE YOU KNOW IS LIVE
i.src = 'http://gfx2.hotmail.com/mail/uxp/w4/m4/pr014/h/s7.png?d=' + escape(Date());
// escape(Date()) is necessary to override possibility of image coming from cache
</script>

Just my 2 cents

10
  • 1
    even thought this is a hack, it got me the work done.
    – JaydeepW
    Commented Apr 21, 2012 at 16:03
  • 1
    This was perfect for differentiating between my server being down and the internet being down. I used Google's logo, assuming that if it's not accessible, then the internet is probably down.
    – elynnaie
    Commented Dec 17, 2013 at 3:32
  • 1
    But what if the browser already has that image in cache, then the test won't reveal what it is supposed to right? It would just fetch it from the local memory and not go online to fetch it? Commented Jun 23, 2015 at 15:30
  • 2
    Well, that's why there's the escape(Date()) portion to the script. So chances that you will have a cached image with the exact time stamp (hh:mm:ss) is pretty slim... Commented Jun 26, 2015 at 17:52
  • Think there is a better image url we could use? One that will always be up, forever and ever!? Or at least 99.999% of the time forever and ever? Commented Mar 11, 2016 at 22:29
14

5 years later-version:

Today, there are JS libraries for you, if you don't want to get into the nitty gritty of the different methods described on this page.

On of these is https://github.com/hubspot/offline. It checks for the connectivity of a pre-defined URI, by default your favicon. It automatically detects when the user's connectivity has been reestablished and provides neat events like up and down, which you can bind to in order to update your UI.

5
  • 4
    This won't work if he can't load jQuery first, which is his problem. Commented Mar 5, 2010 at 2:33
  • 2
    you don't have to get jquery via CDN, but can put it on your server... then this will work :-) Commented Mar 5, 2010 at 2:36
  • 2
    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. Commented Mar 5, 2010 at 2:42
  • 1
    @PhilRykoff that's why I always Google the phrase "isitdown Google.com" to make sure I don't fall for such a fallacy. ;) Commented Sep 12, 2014 at 18:31
  • Sadly, this JS library hasn't been touched since 2017. Commented May 10, 2022 at 15:16
6

You can mimic the Ping command.

Use Ajax to request a timestamp to your own server, define a timer using setTimeout to 5 seconds, if theres no response it try again.

If there's no response in 4 attempts, you can suppose that internet is down.

So you can check using this routine in regular intervals like 1 or 3 minutes.

That seems a good and clean solution for me.

1

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.

5
  • 3
    This doesn't work. He needs to check if the network is there BEFORE getting jQuery, SO THAT HE CAN GET JQUERY. Commented Mar 5, 2010 at 2:34
  • if he is in the page, then he already got JQuery ... am I missing something ? Commented Mar 5, 2010 at 2:36
  • 1
    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. Commented Mar 5, 2010 at 2:40
  • Good point about JQuery, though, the XHR solution is valid. Commented Mar 5, 2010 at 2:44
  • 1
    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. Commented Mar 5, 2010 at 2:46
0

I wrote a jQuery plugin for doing this. By default it checks the current URL (because that's already loaded once from the Web) or you can specify a URL to use as an argument. Always doing a request to Google isn't the best idea because it's blocked in different countries at different times. Also you might be at the mercy of what the connection across a particular ocean/weather front/political climate might be like that day.

http://tomriley.net/blog/archives/111

-3

i have a solution who work here to check if internet connection exist :

$.ajax({
    url: "http://www.google.com",
    context: document.body,
    error: function(jqXHR, exception) {
        alert('Offline')
    },
    success: function() {
        alert('Online')
    }
})
5
  • 6
    This checks if http://www.google.com is reachable. Commented Mar 4, 2014 at 21:49
  • 1
    google.com will always return error like this...
    – shinzou
    Commented Dec 12, 2016 at 9:38
  • 4
    The day google is not reachable is the day internet will die. Commented May 18, 2017 at 11:04
  • kuhaku is correct this just errors
    – Phil3992
    Commented Jul 5, 2017 at 10:38
  • Just out of curiosity... why does it error? Commented Sep 11, 2017 at 20:26
-4

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.

8
  • 1
    well, you can check if google is up/down :-) Commented Mar 5, 2010 at 2:33
  • Why do something like that, if the google API will do it in a cleaner, more readable, programmatic way? Commented Mar 5, 2010 at 2:35
  • 2
    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... Commented Mar 5, 2010 at 2:37
  • 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. Commented Mar 5, 2010 at 2:39
  • 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 Commented Mar 5, 2010 at 2:42
-5

A much simpler solution:

<script language="javascript" src="http://maps.google.com/maps/api/js?v=3.2&sensor=false"></script>

and later in the code:

var online;
// check whether this function works (online only)
try {
  var x = google.maps.MapTypeId.TERRAIN;
  online = true;
} catch (e) {
  online = false;
}
console.log(online);

When not online the google script will not be loaded thus resulting in an error where an exception will be thrown.

2
  • 25
    so cute solution :) A beginner's one Commented Jan 26, 2014 at 0:50
  • That's a really bad solution.
    – Zanon
    Commented Feb 10, 2016 at 14:01

Not the answer you're looking for? Browse other questions tagged or ask your own question.