I cannot tell you how many times I’ve walked into a project that required the following:
- Fancy JavaScript alerts, dialogs, and validation.
- JavaScript assets that will distributed to subsites / satellite sites.
- 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”.
Recent Comments