jQuery: testing and debugging

During my daily work as a web developer, I usually deal with a lot of templates and site themes. Though they're pretty impressive from a visual point of view, they actually lack of consistency and organization when it comes to jQuery. The point is that many of these templates are not thoroughly tested and debugged in various environments. Usually the theme's author chooses a testing environment and a target browser and simply tests his/her code on that environment. Things run smoothly and the author assumes that everything will work just fine in other environments as well. Nothing could be more harmful than this approach. Environments and browsers are different and even though progressive enhancement can actually provide a fallback mechanism for the worst-case scenarios, you should never assume that a code tested in the browser X will work also in the browser Y. Here follows a little list of tips and gotchas to help you with testing and debugging in jQuery.

Goodbye alert, welcome console

Never use alerts. They're clumsy and block the page, not to mention that are extremely tedious in loops. Instead, log everything to the JavaScript console:

if($('div.test').length) {
  console.log($('div.test').length);
} else {

  console.log('div.test not found');

}

Inspect the DOM

If your code generates a brand new DOM structure, always check that such structure has been properly created. Open Firebug or your JavaScript console and check if the element you have clicked actually contains the structure you've created.

Know CSS

jQuery's animations work together with CSS styles. Before adding the jQuery behavior, always check whether your styles work or cause a bug in some browsers. You should never add jQuery before you're 100% sure that your CSS rules work as intended. Also, make sure that your styles won't conflict with your jQuery code, especially if you want to add other styles dynamically.

Performance matters

You should always test the performance of your code in browsers. In that vein, never, ever test first in high-performance browsers. Instead, test in slow browsers first. If your code works well in such browsers, it will work much, much better in other browsers. This is the browser testing order that I follow, in descending order of precedence:

  1. IE
  2. Firefox, Opera
  3. Chrome, Safari

Here are some gotchas for improving your performance:

  • cache variables and references
  • use innerHTML whenever it's possible
  • use array's joining for assembling strings
  • use selector's context
  • use for instead of $.each() or each()

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.