browser - Check if Internet Connection Exists with Javascript? -
this question has answer here:
- detect internet connection offline? 13 answers
how check if there internet connection using javascript? way have conditionals saying "use google cached version of jquery during production, use either or local version during development, depending on internet connection".
the best option specific case might be:
right before 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 easiest way given issue centered around jquery.
if wanted more robust solution try:
var online = navigator.online;
read more w3c's spec on offline web apps, aware work best in modern web browsers, doing older web browsers may not work expected, or @ all.
alternatively, xhr request own server isn't bad of method testing connectivity. considering 1 of other answers state there many points of failure xhr, if xhr flawed when establishing it's connection it'll flawed during routine use anyhow. if site unreachable reason, other services running on same servers unreachable also. decision you.
i wouldn't recommend making xhr request else's service, google.com matter. make request server, or not @ all.
what mean "online"?
there seems confusion around being "online" means. consider internet bunch of networks, you're on vpn, without access internet "at-large" or world wide web. companies have own networks have limited connectivity other external networks, therefore considered "online". being online entails connected a network, not availability nor reachability of services trying connect to.
to determine if host reachable network, this:
function hostreachable() { // handle ie , more capable browsers var xhr = new ( window.activexobject || xmlhttprequest )( "microsoft.xmlhttp" ); var status; // open new request head root hostname random param bust cache xhr.open( "head", "//" + window.location.hostname + "/?rand=" + math.floor((1 + math.random()) * 0x10000), false ); // issue request , handle response try { xhr.send(); return ( xhr.status >= 200 && (xhr.status < 300 || xhr.status === 304) ); } catch (error) { return false; } }
you can find gist here: https://gist.github.com/jpsilvashy/5725579
details on local implementation
some people have commented, "i'm being returned false". that's because you're testing out on local server. whatever server you're making request to, you'll need able respond head request, of course can changed if want.
Comments
Post a Comment