Posts Tagged ‘dynamic jquery’

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”.

Page 1 of 11

Latest Posts

The United West

March 29th, 2011 by Tim Selaty

WordPress 3.1 Helicon ISAPI_Rewrite Rules and Permalink Structure

March 6th, 2011 by Tim Selaty

One of my clients is using WordPress on an IIS server and is using a product called “Helicon” (more…)

WordPress 3.1 Upgrade – Frontend Blank Site, Backend Okay (IIS)

March 6th, 2011 by Tim Selaty

Shoot. You just upgraded your WordPress installation to the latest version (3.1 for me) and all of a (more…)

CodeIgniter HTACCESS remove index.php and add trailing slash

February 18th, 2011 by Tim Selaty

Here is a quick HTACCESS snippet that will add the trailing slash (ex: http://domain.com/mycontroller to http://domain.com/mycontroller/) and will (more…)