Do you want to prevent loading JQuery twice?  JQuery (at least through 1.4) doesn’t work when you include it more than once.

At work I ran across a strange problem that often comes up in content management systems.  The scenario works like this:

  • The content management system uses JQuery in its latest version but not in earlier versions
  • A skin designer uses JQuery in the design of a skin
  • A plugin developer uses JQuery in the implementation of a plugin
  • Someone who writes custom content for a page wants to use JQuery for a page

All these different people want to use JQuery – but the JQuery framework does not function properly if it is included more than once on a web page.  There’s also no conditional include in HTML (or any include functionality at all, which I’ve always thought to be a glaring omission).

I wrote a wrapper that you can include instead of JQuery that doesn’t include JQuery if it’s already there. It’s based up on a post by FlySwat but the problem with FlySwat’s is that you have to put some extra code in front of your JQuery code every time. To use my version of the wrapper, all you have to do is use a different function other than $(document).ready to start your scripts at page ready time.

Here’s my “jquery.js” which you can put on a page as often as you like:

if (typeof(loadJSInclude) == 'undefined') {
 function loadJSInclude(scriptPath, callback)
 {
   var scriptNode = document.createElement('SCRIPT');
   scriptNode.type = 'text/javascript';
   scriptNode.src = scriptPath;

   var headNode = document.getElementsByTagName('HEAD');
   if (headNode[0] != null)
      headNode[0].appendChild(scriptNode);

   if (callback != null)    
   {
     scriptNode.onreadystagechange = callback;            
     scriptNode.onload = callback;
   }
 }

 function loadJQuery(task) {
   if (typeof(jquery) == "undefined")
   loadJSInclude('/js/jquery-1.4.1.min.js', function() {
     $(document).ready(task)
   });
   else
     $(document).ready(task());
 }
}

And then, to start your JQuery operations, use loadJQuery()  instead of $(document).ready()

loadJQuery(function () {
  .. your jquery stuff here ..
  $('#boomboom').click( function() {
  alert("BOOM!");
  });
);