How to include jQuery dynamically, aka, check to see if it exists

I cannot tell you how many times I’ve walked into a project that required the following:

  1. Fancy JavaScript alerts, dialogs, and validation.
  2. JavaScript assets that will distributed to subsites / satellite sites.
  3. Of these sites, some may or may not already have these assets already defined.

What I’m referring to specifically is jQuery. While building a tasty and user-friendly form.. I needed a way to check to see if jQuery didn’t exist, and if it didn’t include it dynamically by append it to the HEAD tag. This is commonly referred to ‘including jQuery dynamically’. Often times different phrases such as ‘check to see if jQuery is defined’, ‘lazy load jQuery’, ‘!window.jQuery’

Here is the JavaScript code to make the magic happen.

if(!(window.jQuery && window.jQuery.fn.jquery == '1.3.2')) {var s = document.createElement('script');s.setAttribute('src', 'http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js');s.setAttribute('type', 'text/javascript');document.getElementsByTagName('head')[0].appendChild(s);}

As a recap, here is what the snippet above does. “Check to see if jQuery is defined. If it’s not, grab jQuery from Google’s API and include it in the HEAD tag”.

Share and Enjoy:
  • Print
  • Twitter
  • Facebook
  • Google Bookmarks
  • Digg
  • del.icio.us
  • StumbleUpon
  • Yahoo! Bookmarks

4 Responses to “How to include jQuery dynamically, aka, check to see if it exists”

  1. I found your blog post while searching Google. Very relevant especially as this is not an issue which a lot of peaople know that well

  2. I was looking for this. thanks.

  3. This is great but i am wondering how you would make include the latest version of jquery or check for latest version?

  4. Aaron, try this Google API code.

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript" charset="utf-8"></script>

Leave a Reply

Latest Posts

JomSocial Popup Dialog Ajax Won’t Finish Loading

March 25th, 2010 by Tim Selaty

JomSocial is a great extension built for the wonderful Joomla! that comes with many features people desire in (more…)

Share and Enjoy:
  • Print
  • Twitter
  • Facebook
  • Google Bookmarks
  • Digg
  • del.icio.us
  • StumbleUpon
  • Yahoo! Bookmarks

United we Stand for Americans

February 18th, 2010 by Tim Selaty

The Idea: To create a web presence that is consistent and relays the idea of “conservative values” to (more…)

SellerBuzz

February 17th, 2010 by Tim Selaty

Seller Buzz is for Online Sellers just starting out in the world of eCommerce. Seller Buzz is also (more…)

Timberhawk

February 17th, 2010 by Tim Selaty

At Timberhawk we use high-tech equipment and software to produce a stronger, more accurate and faster built home. (more…)