Check if Internet Connection Exists with jQuery? [duplicate]
Asked Answered
J

9

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".

Jonquil answered 5/3, 2010 at 2:23 Comment(10)
How does the javascript get downloaded to the browser?Portion
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.Jonquil
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.Contango
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?Portion
I 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.Jonquil
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.Contango
@Portion 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 connectionsHelenahelene
@Portion Ever heard of cache manifest offline web apps.Ruby
Since PWAs are a thing now, I guess this question makes a lot of sense nowMurder
I'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.Jorgenson
C
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.

Contango answered 5/3, 2010 at 2:23 Comment(20)
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.Job
Nope, it is available in firefox: developer.mozilla.org/En/DOM/Window.navigator.onLineContango
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.Feeling
problem was that the different browser developers couldn't decide what "online" meansSyrupy
Always returning false.Biparty
I'd like to point out that this may not work in local development environment depending on your network configuration.Contango
"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.Eleusis
@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.Contango
@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.Eleusis
@1.21gigawatts okay that's true.Contango
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 falseCocksure
@ImanMohamadi this was addressed in my answer.Contango
@JosephSilvashy yea your answer is complete,Cocksure
@JosephSilvashy please see the edit I just made regarding your return statement and using "and" in addition to "or" conditions...Remorseful
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 xhr.spec.whatwg.org"Angy
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.Knives
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.Possibly
Also, the request host needs CORS enabled if you want to check a foreign host.Cocklebur
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.Basenji
@VishnuTAsok I've outlined what the difference between connected to a network vs determining that a hostname is reachable.Contango
G
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

Goss answered 9/11, 2010 at 22:43 Comment(10)
even thought this is a hack, it got me the work done.Uniocular
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.Williamwilliams
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?Ruggiero
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...Goss
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?Kiki
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.pngGoss
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.Toggery
This excels where navigator.onLine fails.Unpin
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!Iatric
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.Maletta
D
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.

Donnettedonni answered 5/3, 2010 at 2:31 Comment(5)
This won't work if he can't load jQuery first, which is his problem.Riddell
you don't have to get jquery via CDN, but can put it on your server... then this will work :-)Donnettedonni
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.Riddell
@PhilRykoff that's why I always Google the phrase "isitdown Google.com" to make sure I don't fall for such a fallacy. ;)Laconism
Sadly, this JS library hasn't been touched since 2017.Maletta
F
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.

Fionafionna answered 21/1, 2012 at 16:28 Comment(0)
M
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.

Muntjac answered 5/3, 2010 at 2:27 Comment(5)
This doesn't work. He needs to check if the network is there BEFORE getting jQuery, SO THAT HE CAN GET JQUERY.Riddell
if he is in the page, then he already got JQuery ... am I missing something ?Muntjac
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.Riddell
Good point about JQuery, though, the XHR solution is valid.Muntjac
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.Riddell
V
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

Vladivostok answered 25/5, 2012 at 18:51 Comment(0)
T
-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')
    }
})
Traverse answered 30/1, 2014 at 15:16 Comment(5)
This checks if http://www.google.com is reachable.Contango
google.com will always return error like this...Lympho
The day google is not reachable is the day internet will die.Deonnadeonne
kuhaku is correct this just errorsCavalier
Just out of curiosity... why does it error?Englut
R
-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.

Riddell answered 5/3, 2010 at 2:32 Comment(8)
well, you can check if google is up/down :-)Donnettedonni
Why do something like that, if the google API will do it in a cleaner, more readable, programmatic way?Riddell
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...Donnettedonni
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.Riddell
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 xhttprDonnettedonni
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.Riddell
I felt like the solution should not require access to any service, getting the google API loaded will naturally require internet access.Contango
google.load("jquery"); ???Lympho
B
-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.

Buckbuckaroo answered 17/7, 2013 at 19:6 Comment(2)
so cute solution :) A beginner's oneFrock
That's a really bad solution.Ludwig

© 2022 - 2024 — McMap. All rights reserved.