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".
-
5How does the javascript get downloaded to the browser? – S.Lott Mar 05 '10 at 02:36
-
2sometimes 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 Mar 05 '10 at 07:21
-
7I'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. – JP Silvashy Mar 05 '10 at 20:06
-
1How 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 Mar 06 '10 at 06:02
-
1I live in wine country and the internet is really bad out here, like in the mountains mountains, with bears and lions and everything. sometimes when I'm developing I'd just rather shut it off than deal with slow load times. But I want to have it so if I turn back on the internet, I don't have to change a thing to start using the hosted javascript files. Does that make sense? If I turn off the internet, I can still load the local javascript into Safari so that's not an issue. – Lance Mar 07 '10 at 09:05
-
If you're developing in a framework like Rails you can just have your development environment use a different head for your HTML, then you can just work as you please and your production env can have links to all the JS libs you use via google's API. – JP Silvashy Mar 11 '10 at 21:27
-
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 – Daniel Cheung Feb 06 '14 at 05:41
-
@S.Lott Ever heard of cache manifest offline web apps. – noɥʇʎԀʎzɐɹƆ Jul 13 '15 at 17:50
-
Since PWAs are a thing now, I guess this question makes a lot of sense now – Jay Ghosh Apr 25 '18 at 18:10
-
1I've got a use case for exactly this. We produce software that includes an overview runs on wall-mounted displays. A very common failure mode is that the site will lose connection "for a few minutes" periodically throughout the day. – Mark Harrison Sep 24 '19 at 09:18
9 Answers
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.

- 479
- 1
- 12
- 27

- 46,977
- 48
- 149
- 227
-
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. – Buhake Sindi Mar 11 '10 at 21:36
-
Nope, it is available in firefox: https://developer.mozilla.org/En/DOM/Window.navigator.onLine – JP Silvashy Mar 12 '10 at 19:30
-
2It'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 Oct 25 '10 at 13:18
-
8problem was that the different browser developers couldn't decide what "online" means – Thariama Oct 26 '11 at 12:42
-
-
I'd like to point out that this may not work in local development environment depending on your network configuration. – JP Silvashy Oct 20 '13 at 17:24
-
"Online" to rest of the world (and routers and firewall vendors) means being able to connect to the internet (ie a website). Technically, that means you would be able to connect to a server / service beyond your ISP or at least to it (if you can't reach beyond that that's another problem). To resolve any confusion you should introduce a navigator.onNetwork or something similiar. – 1.21 gigawatts Jan 12 '14 at 15:04
-
@1.21gigawatts this is not true, being able to access a website doesn't have anything directly to do with your ISP, you can host a website in an internal network which is only available to users inside your network and not users of the same WAN. – JP Silvashy Jan 13 '14 at 19:27
-
@JosephSilvashy - my point is that people equate internet as online. you're talking about an intranet. people don't equate intranet as online. i'm saying the nomenclature of our society is online means connected to the rest of the world. – 1.21 gigawatts Jan 13 '14 at 22:52
-
-
6navigator.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 – Iman Mohamadi Apr 27 '14 at 08:13
-
-
-
@JosephSilvashy please see the edit I just made regarding your return statement and using "and" in addition to "or" conditions... – ganders Sep 29 '14 at 20:02
-
Chrome now raises this deprecation warning: "Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check http://xhr.spec.whatwg.org/" – Jay Sep 01 '15 at 05:17
-
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. – Ashish Choudhary Mar 11 '16 at 05:06
-
What a wonderful language where `isNan(undefined===true` and the browser devs (I expected better Webkit) can't even decide on what the term "online" means. Sounds like lazy development from where I'm sitting. – Mar 29 '18 at 23:54
-
1Also, the request host needs CORS enabled if you want to check a foreign host. – CodeBrauer Aug 31 '20 at 08:46
-
navigator.onLine in browsers tells you if your device has a connection to any network and not specifically to the internet. This means if your internet connection goes down but the network stays connected, the application would still think it’s online. – Vishnu T Asok Apr 04 '22 at 10:35
-
@VishnuTAsok I've outlined what the difference between connected to a network vs determining that a hostname is reachable. – JP Silvashy Apr 04 '22 at 15:30
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

- 634
- 6
- 15
-
1
-
1This 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 Dec 17 '13 at 03:32
-
1But 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? – Matt Welander Jun 23 '15 at 15:30
-
2Well, 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... – morespace54 Jun 26 '15 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? – wayofthefuture Mar 11 '16 at 22:29
-
Well as mentioned earlier, you could try with any image really. Something like the Google logo should do it for a while I guess `https://www.google.com/images/nav_logo242.png` – morespace54 Apr 07 '16 at 23:25
-
There's no such thing as a permanent image...but this is a great solution! Rather than use google's logo..it's better to use a logo on your own site. This will also allow you to determine whether or not to make your request available only after your own site is available. – skidadon Jun 17 '16 at 04:43
-
-
It worked, but I created a huge memory leak by placing that code in a function called 1 / s: the image was not disposed, so memory usage kept on going up. Don't repeat my mistake! – Davide Andrea Oct 03 '17 at 16:49
-
This is a great solution. It avoids any CORS issues. I ended up using `https://www.google.com/favicon.ico`, which is Google's favicon - unlikely to change or be unavailable. – seymore_strongboy May 10 '22 at 15:16
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.

- 11,999
- 3
- 39
- 63
-
4This won't work if he can't load jQuery first, which is his problem. – Mike Trpcic Mar 05 '10 at 02:33
-
2you don't have to get jquery via CDN, but can put it on your server... then this will work :-) – Phil Rykoff Mar 05 '10 at 02:36
-
2He'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 Mar 05 '10 at 02: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. ;) – BlackVegetable Sep 12 '14 at 18:31
-
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.

- 20,746
- 15
- 92
- 109
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.

- 784
- 10
- 24

- 17,257
- 2
- 39
- 75
-
3This doesn't work. He needs to check if the network is there BEFORE getting jQuery, SO THAT HE CAN GET JQUERY. – Mike Trpcic Mar 05 '10 at 02:34
-
if he is in the page, then he already got JQuery ... am I missing something ? – Soufiane Hassou Mar 05 '10 at 02:36
-
1Re-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 Mar 05 '10 at 02:40
-
-
1As 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 Mar 05 '10 at 02:46
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.

- 830
- 3
- 12
- 27
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')
}
})

- 17,068
- 9
- 59
- 93

- 57
- 1
-
6
-
1
-
4The day google is not reachable is the day internet will die. – Abdul Sadik Yalcin May 18 '17 at 11:04
-
-
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.

- 25,305
- 8
- 78
- 114
-
1
-
Why do something like that, if the google API will do it in a cleaner, more readable, programmatic way? – Mike Trpcic Mar 05 '10 at 02:35
-
2for 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... – Phil Rykoff Mar 05 '10 at 02: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. – Mike Trpcic Mar 05 '10 at 02: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 – Phil Rykoff Mar 05 '10 at 02:42
-
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 Mar 05 '10 at 02:43
-
I felt like the solution should not require access to any service, getting the google API loaded will naturally require internet access. – JP Silvashy Nov 18 '13 at 19:39
-
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.

- 109
- 7