jQuery pitfalls to avoid [closed]

jQuery pitfalls to avoid [closed]

I am starting a project with jQuery.
What pitfalls/errors/misconceptions/abuses/misuses did you have in your jQuery project?

Solutions/Answers:

Solution 1:

Being unaware of the performance hit and overusing selectors instead of assigning them to local variables. For example:-

$('#button').click(function() {
    $('#label').method();
    $('#label').method2();
    $('#label').css('background-color', 'red');
});

Rather than:-

$('#button').click(function() {
    var $label = $('#label');
    $label.method();
    $label.method2();
    $label.css('background-color', 'red');
});

Or even better with chaining:-

$('#button').click(function() {
    $("#label").method().method2().css("background-color", "red"); 
});

I found this the enlightening moment when I realized how the call stacks work.

Edit: incorporated suggestions in comments.

Solution 2:

Understand how to use context. Normally, a jQuery selector will search the whole doc:

// This will search whole doc for elements with class myClass
$('.myClass');

But you can speed things up by searching within a context:

var ct = $('#myContainer');
// This will search for elements with class myClass within the myContainer child elements
$('.myClass', ct);

Solution 3:

Don’t use bare class selectors, like this:

$('.button').click(function() { /* do something */ });

This will end up looking at every single element to see if it has a class of “button”.

Related:  Google Maps SVG marker doesn't display on IE 11

Instead, you can help it out, like:

$('span.button').click(function() { /* do something */ });
$('#userform .button').click(function() { /* do something */ });

I learned this last year from Rebecca Murphy’s blog

Update – This answer was given over 2 years ago and is not correct for the current version of jQuery.
One of the comments includes a test to prove this.
There is also an updated version of the test that includes the version of jQuery at the time of this answer.

Solution 4:

Try to split out anonymous functions so you can reuse them.

//Avoid
$('#div').click( function(){
   //do something
});

//Do do
function divClickFn (){
   //do something    
}

$('#div').click( divClickFn );

Solution 5:

  • Avoid abusing document ready.
  • Keep the document ready for initialize code only.
  • Always extract functions outside of the doc ready so they can be reused.

I have seen hundreds of lines of code inside the doc ready statement. Ugly, unreadable and impossible to maintain.

Solution 6:

While using $.ajax function for Ajax requests to server, you should avoid using the complete event to process response data. It will fire whether the request was successful or not.

Related:  Disable hover effects on mobile browsers

Rather than complete, use success.

See Ajax Events in the docs.