Monthly Archives: November 2010

5 Common Ways to Abuse jQuery

jQuery is great. It is powerful and quick. But with any power comes abuse. Here are some common ways to jQuery is abused.

 

1) Overuse of .ready()

Problem: Much JavaScript should run immediately after an element closing tag.

How bad? Better to shatter a mirror

Why: Users will often start using the page before it finishes loading. Google Analytics and other scripts can cause the DOMContentLoaded event fire long after the page appears to be loaded.

Instead do: Add a script block immediately after the element! For example, if I want to focus in on the first element in the form, add document.getElementById('id').focus() in a script block right after the input tag. If not, I might start filling in the form; when the page finishes loading a few seconds later, I’ll be in for a nasty surprise–the cursor will snap back to the first input!

 

2) Using .is(‘.class’)

Problem: performance.

How bad? Like a Zombie

Why: jQuery runs through an awful lot of Sizzle code instead of just checking HTMLElement#className.

Instead do: .hasClass(‘class’)

 

3) Using .live()

Problem: Terrible performance, some features are not supported.

How bad? An angel loses its wings

Why: jQuery attaches the listener to the document.

Instead do: .delegate(). It allows you attach the listener to the element(s) you want to. Attaching to the document is almost always too high. I think .delegate() was added as a correction to .live()–.live() should have never been added.

 

4) Repeated Calls

Problem: Too many users call $(selector) every time they reference the object–even one line after another.

How bad? Lightning to the forehead

Why: jQuery re-queries the document on every call.

Instead do: If you plan to reference the object later, store it in a variable!

 

5) Not Knowing JavaScript

Problem: Some jQuery users don’t know JavaScript. Even worse, some don’t even know that jQuery is JavaScript!

How bad? Tomato to the face

Why: You do a disservice to yourself and your web app if you don’t know the basics of JavaScript. It’s like pulling the trigger of a gun without knowing which way the bullet will come out.

Instead do: Learn how to do some things in JavaScript without jQuery. For example, experiment with document.getElementById and HTMLElement#style.