Problems with jQuery? Make sure you upload the right library

Today I’ve run into a problem on a client’s site, and I want to share with you how I figured it out.

A couple of weeks ago I wrote a very simple accordion function to make a description appear/disappear inside a download box. Today, my client wrote to me saying that the accordion didn’t work anymore, and the description text was always visible. First thing, I checked with Firebug that the script was correctly added to the head of the page. I always use the plugin Header and Footer to add my scripts to posts and pages, and it always worked but you never know. My first guess was that the script for some reason was added before the jQuery library is loaded. In such case the script would not work because it uses a library that is not yet available. However, that was not the case.

When you find yourself in such situation it’s easy to get frustrated. The secret is to stay calm and analyze the situation. The script was working previously, so it could not be a bug in the script itself. After some research I tried to see if the Firebug console was giving me any error. And here I started to understand. I got an error saying TypeError: $(…).accordion is not a function. So, that was definitely a problem with the jQuery library. It didn’t take long to figure it out. The accordion is a function of jQuery UI which is a separate library from the standard jQuery library. The WordPress theme that my client was using uploaded the jQuery library but not the jQuery UI library, so the accordion didn’t work.

To fix that I simply added the two following lines to all the head sections of pages and posts through my Header and Footer plugin:


<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/i18n/jquery-ui-i18n.min.js"></script>

So, why did it work before? I think that for a lucky case some plugin loaded the library. The client disabled a few plugins in the last two days and that broke my script.

Lesson learned, always verify that you have the right libraries loaded before writing any script, don’t assume that they are there. It will save you a lot of frustration and debugging hours!


So, what do you think ?