jQuery Loading Via Google With Fallback

This page explains how to load JQuery via the GoogleAPIs server, with a fallback trying to use your own server.

We do this because:

  • The Google server may be unavailable due to network problems.
  • Some countries and companies are blocking the Google server.
  • We can use local JQuery files when we are offline.

    How to load JQuery via Google

    To load the JQuery library via the GoogleAPIs server, we use a script tag with a src path specifying which script version number we want:
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
    

    How to detect if JQuery loads successfully

    To detect if JQuery loads successfully via the GoogleAPIs server, we use Javascript to detect whether the JQuery variable exists:
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
      <script>
        if (jQuery){ 
          alert("success");
        }
        else{
          alert("failure");
        }
      </script>
    

    How to dynamically load a Javascript src URL

    To dynamically load a script while the HTML page is loading, we create a function that uses the Javascript's command document.write to write a script tag with the source URL as a parameter:
      <script>
        function load_script(src){
          document.write(unescape("%3Cscript src='"+src+"' type='text/javascript'%3E%3C/script%3E");
        }
      </script>
    

    How to load JQuery then JQueryUI

    To load JQuery, then load JQueryUI:
      <script>
        function load_script(src){
          document.write(unescape("%3Cscript src='"+src+"' type='text/javascript'%3E%3C/script%3E");
        }
      </script>
    
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
      <script>
        if (!jQuery){ 
          load_script("http://example.com/anywhere/you/want/jquery.min.js");
        }
      </script>
    
      <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/jquery-ui.min.js"></script>
      <script>
        if (!jQuery.ui){ 
          load_script("http://example.com/anywhere/you/want/jquery-ui.min.js");
        }
      </script>
    



    What's Next?

    blog comments powered by Disqus