This question already has an answer here:
- Detect the Internet connection is offline? 16 answers
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".
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
anddown
, which you can bind to in order to update your UI.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?
Just my 2 cents
A much simpler solution:
and later in the code:
When not online the google script will not be loaded thus resulting in an error where an exception will be thrown.
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.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:
The google API documentation can be found here.
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.