Home  >  

From the "duh" files - don't include jQuery twice

Author photo
AddThis Social Bookmark Button

Ok, so this really does belong in the "duh" files, but it threw me for a loop last night. I was updated my blog to a new design (seen here) when all of a sudden I noticed jQuery errors. Specifically errors with a plugin that I knew worked fine. To make it worse, I saw it sometimes but not others.

I went into Firebug to see if perhaps some of the JavaScript wasn't loading on the new server - and that's when I noticed it. My request was loading jQuery twice. I didn't do it on purpose. My new blog design included jQuery in the template, but I also had blog entries that made use of jQuery as well. The combination of the new design and the blog entries with jQuery in it created the error. Here is a super simple example to show you this in action.

<html>

<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="myplugin.js"></script>
<script>
$(document).ready(function() {
 	$().console("Woot")
})
</script>
</head>

<body>
</body>
</html>

My plugin was rather simple. I had not yet written a plugin so I took a quick look at this tutorial for help. I whipped up the following:

(function($) { 
 	$.fn.console = function(s) { 
  	 if(console) console.log(s)	
  	 }; 
})(jQuery);

Yeah, not rocket science, but it worked fine. To recreate the bug, I simply added in another jQuery request.

<html>

<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="myplugin.js"></script>
<script>
$(document).ready(function() {
 	$().console("Woot")
})
</script>
</head>

<body>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
</body>
</html>

And immediately got the error that plagued me last night: $().console is not a function. Pretty obvious once you think about it, but I'm so used to looking for cases where a library didn't load that I was surprised that I got impacted by a library loading twice!

Read more from Raymond Camden. Raymond Camden's Atom feed cfjedimaster on Twitter

Comments

3 Comments

DanWilson said:

Yeah, that has gotten me once or twice in the past. It can be non-obvious when using several layers and UI frameworks.


Thanks for posting, you'll help someone from pulling out their hair.

Dan Wilson

mrm said:

Why $() ? Simply using $ works

@mrm: I guess just force of habit.

Leave a comment


Tag Cloud

Question of the Week: Dream App

If you had an unlimited budget and unlimited resources what application would you build and why would you build it?

Answer

Latest Features

Recommended for You

@InsideRIA on Twitter

Archives

  • Or, visit our complete archive.  

About This Site

Welcome to the premiere community site for all things RIA sponsored by O'Reilly Media and Adobe Systems Incorporated.