Check jQuery Loads (fallback & check)

Load alternate version of jQuery: Linking out to a jQuery library on a hosted server is all very well, but what if the link to the external host fails to load? We can write a script to check if the remotely hosted version of jQuery loaded, then link to a local fallback version of the library if it didn't.

jQuery status: jQuery failed to load.

Notes:

The basic code structures used in this code example are found in most scripting/programming languages.


See the code:

<!-- Link to externally hosted jQuery library (broken deliberately...) -->
<script type="text/javascript" src="http://codexxxx.jquery.com/jquery-latest.min.js"></script>
	
<!-- This script checks if jQuery loaded successfully from the remote server.
If not, it loads a pre-downloaded backup version stored locally in the site structure. -->
<script type="text/javascript">
    // Create an empty variable for loading messages about the jQuery loading status
    var $msg = "";
		
    // Check if jQuery exists. The window.jQuery object will be FALSE if jQuery hasn't loaded.
    if (window.jQuery) {
        // jQuery loaded successfully from the CDN.
        // Put the CDN success message into the empty $msg variable
        $msg = "jQuery loaded from the CDN source";
    } else {
        // If we are here then CDN jQuery didn't load, so use Javascript to write a 
        // HTML script tag to load the local backup jQuery library found in the js folder
        document.write("<script type=\"text/javascript\" src=\"js/jquery-1.10.2.js\"><\/script>");
        // Put the local jQuery success message into the empty $msg variable
        // Note we haven't checked if the local version loaded successfully,
        // but we can deal with that when we write out the message!
        $msg = "jQuery loaded from a local source";
    }
</script>

<script>
    // Use jQuery to change the default contents of the #message element on the page.
    // Note: If neither version of jQuery loaded the message will not be changed and
    // the default failure message already in the P will still be displayed.
    $(document).ready(function() {
        if ($msg !="") {
            $('#message').text('jQuery status: ' + $msg);
        }
    });
</script>