A fresh mix of code snippets and tutorials

Include Google jQuery with Local Fallback

Here’s a nice snippet of JavaScript for including Google-hosted jQuery with fallback.

Because you never know when Google won’t be available, either due to network congestion, failure, or other reasons. In fact, Google’s domain is banned in some countries, so best to provide a fallback script.

Method 1

Place this code in the <head> section or just before the closing </body> tag:

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script type="text/javascript">
	if (typeof jQuery == 'undefined'){
	    document.write(unescape("%3Cscript src='/js/jquery.min.js' type='text/javascript'%3E%3C/script%3E"));

Here is another/simpler way to do it:

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="/js/jquery.min.js">\x3C/script>')</script>

Edit the path “/js/jquery.min.js” to match the location of jQuery, either a local copy on your server or an alternate external location such as a CDN. Note that the latest version of jQuery also is available via the jQuery site, located at:


Method 2

Here is an alternate version of the previous method that uses the same basic principle but with more concise syntax. To include Google-hosted jQuery with a local/alternate fallback, add the following code snippet:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script> 
<script>!window.jQuery && document.write('<script src="/js/jquery.min.js"><\/script>')</script>

As before, you can include that code in the document <head> or just before the closing </body> tag. Remember to test that everything is working as expected.

Bonus: dynamic SSL detection

Here is a quick JavaScript snippet for determining whether the current page is served via SSL/HTTPS or not:

var protocol = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");

So you can either keep your local paths relative, or use this if SSL may be in play.

Good timez.


★ Pro Tip: