Skip to content Skip to sidebar Skip to footer

How To Check If The User Has The Connection To The Internet

In my page,I have to read the weather information from a third part site,then show the weather in the div if the user has the connection to the internet. If not,I will show some lo

Solution 1:

For your usecase, the best way would be to check the error/return code for the weather content you're loading. If it somehow errors or doesn't load, display your local content.

If you still want to insist on checking connectivity by loading a JS library, you can do something akin to the following:

<scriptsrc="https://ajax.googleapis.com/ajax/libs/prototype/1.7.0.0/prototype.js"></script><script>if (typeofwindow.$ !== 'function') {
         window.noInternet = true;
         document.write('<script src="http://mylocalserver/prototype.js"></scri' + 'pt>');
    }
</script>

Possibly replacing 1.7.0.0 with your desired version of prototype.js

Solution 2:

Each JS library I know (Mootools/ JQuery) when they do AJAX, they also manage different return codes. One of those codes is "server not reachable" (find the relevant numeric code). You can check the return code and act upon it. Learn the specific API you use to see how to get those codes.

Since you say that some times the user won't have an outside connection, I would try to include (JSONP) a script from the queried site, which in turn loads the actual content, while this script is not active, show the local content. I would do this entire process using timed loop (setInterval)

Solution 3:

What about checking if jquery is loaded? This might help.. http://jquery-howto.blogspot.com/2009/03/check-if-jqueryjs-is-loaded.html

NOTE: Here we are checking for jQuery function being defined or not. This is a safe way to check for jQuery library being loaded. In case you are not using any other javascript libraries like prototype.js or mootools.js, then you can also check for $ instead of jQuery.

Does it help when you change your check from if ($) to if (jquery)?

Post a Comment for "How To Check If The User Has The Connection To The Internet"