WordPress Code Snippets

A fresh mix of code snippets and tutorials

Include Google jQuery with Local Fallback

258

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

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

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:

http://code.jquery.com/jquery-latest.js

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:

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.

Related


Show Support

Like our new Facebook Page to show support!