211

I am starting a project with jQuery.

What pitfalls/errors/misconceptions/abuses/misuses did you have in your jQuery project?

2
  • 4
    This should not have been closed for being "not constructive". Some very helpful answers have materialized and the question has been starred 220 times now. Please vote to reopen, if you have sufficient karma.
    – Roy Prins
    Jan 4, 2015 at 8:52
  • Seems to me, jQuery is a pitfall in itself
    – birgersp
    Aug 6, 2015 at 8:10

27 Answers 27

189

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.

9
  • 16
    +1 for the youtube link. holy crap i learned a lot.
    – Jason
    Aug 4, 2009 at 20:39
  • 23
    I think assigning things to local variables is great but don't forget about the power of chaining (from your example): $("#label").method().method2().css("background-color", "red"); Aug 4, 2009 at 22:49
  • The YouTube video was great. I've seen other Google presentations on the subject and I still learned a few things! Thanks! Aug 5, 2009 at 21:49
  • +1 for the link as well, excellent! Aug 7, 2009 at 4:26
  • 7
    It's kind of a convention to use a dollar sign for variables with jQuery context. So you may wanna write var $label = $('#label');
    – Tim Büthe
    Apr 14, 2010 at 12:01
91

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);
6
  • 9
    Aaaaaaah! Well, that's about 1,000,000 of my bugs fixed. +1
    – jammus
    Aug 6, 2009 at 14:53
  • 4
    It seems your last point is incorrect - groups.google.co.uk/group/jquery-dev/browse_thread/thread/…
    – James
    Aug 14, 2009 at 12:28
  • 1
    Thanks for pointing this out JP. Now, what to do... Should I delete my answer so no one else goes hog wild and changes their code for nothing?
    – slolife
    Aug 14, 2009 at 16:47
  • Nah, it's still a good point, optimization-wise. :)
    – James
    Aug 14, 2009 at 21:03
  • 2
    jQuery checks to see if the context is an instace of jQuery so there is no reason for [0]. $('.myClass', ct); or if you know ct is an instance of jQuery you can use find ct.find(".myClass")
    – gradbot
    May 14, 2011 at 21:04
63

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".

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.

11
  • 6
    I was also under the impression that the reverse was true. Perhaps this is the case in browsers that don't implement getElementsByClassName, but otherwise you are just giving jQuery more work to do. I would very much like to see Rebecca post some benchmarks :) Oct 2, 2009 at 17:40
  • 7
    You're REDUCING the amount of work it has to do. It's like telling somebody to get your socks out of the drawer in your dresser instead of telling them to get the socks out of your room. Reduces the amount of 'looking' it has to do substantially.
    – Sneakyness
    Dec 31, 2009 at 7:52
  • 4
    The reverse is true when you are writing CSS (at least including the element tag). See code.google.com/speed/page-speed/docs/…
    – kmiyashiro
    Feb 4, 2011 at 23:13
  • 7
    @Sneakyness Not everything has an accurate analogue of real life. For example, $('.b') could use document.getElementsByClassName('b') if the browser supports it, but doing $('a.b') will cause it to get all matching elements with class b and then confirm they are anchors in a two stage operation. The latter sounds like more work to me. For a real life analogy, try this: Find all socks in my room. Now, throw out ones which are not in my dresser.
    – alex
    Mar 18, 2011 at 7:03
  • 2
    I believe the misconception on selectors is due to the fact that in older versions of jquery, it was faster to do $('#foo') rather than $('div#foo'), since by definition, an id is unique. I'm pretty sure this was fixed in later releases however, but that recommendation applied only to ids, not other types of selectors
    – Alex Heyd
    Mar 18, 2011 at 19:54
36

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 );
8
  • 20
    I think this applies to roughly the same degree that synchronous (inline) code should be broken up into named functions. If you've got a chunk of code that is begging to be given a name, then go for it. But don't move the code out of line simply because you're wrapping it inside a function; anonymous functions exist for good reason. Aug 4, 2009 at 19:23
  • 4
    Actually I like to give 'name' to my function. It is very useful when you are debugging the code and instead of seeing an endless list of anonymous functions, you see properly named functions. Aug 4, 2009 at 19:47
  • 1
    Your point is well taken, and I've probably been tripped by this myself a few times. Even so, "roughly the same degree" still works for me. Aug 4, 2009 at 20:48
  • 1
    esp. if the binding is happening in a loop! Aug 7, 2009 at 18:17
  • Named functions also benefit you greatly when debugging; nothing sucks more than looking at a callstack 8 levels deep that has nothing but (anonymous). Read more on this tip here: stackoverflow.com/questions/182630/jquery-tips-and-tricks/…
    – ken
    Dec 29, 2010 at 21:39
34
  • 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.

3
  • 6
    +1. In general, most of the jQuery code I have seen uses functions with hundreds of lines. I don't know why 'jQuery developers' don't like to use smaller functions. Aug 4, 2009 at 19:28
  • 6
    @SolutionYogi because most are just JS noobs?
    – adamJLev
    Jun 16, 2010 at 5:14
  • I'm all for not putting very long functions in document ready, that's good advice. However, making many small component functions that are run from an overarching function that isn't in document ready isn't necessarily the best practice. If the overarching function is the only one that uses those pieces of code you're better off putting it all in the one function even if it's harder to read. Calling functions has a lot of overhead and if you're only using the code in one context it should be avoided.
    – sage88
    Sep 20, 2013 at 16:42
34

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.

Rather than complete, use success.

See Ajax Events in the docs.

9
  • 1
    I've been back and forth on success vs complete, can you expand on why you think complete is better?
    – Neil N
    Aug 4, 2009 at 19:00
  • 1
    I'm not saying complete is better. What I was trying to say is that you need to avoid misleading use of complete and should use success in order to be able to process the response data. Aug 4, 2009 at 19:03
  • 2
    Well it always gets called. However I would disagree. Complete is best for hiding a loading gif etc. You should use the success for handling the response and the error for any errors of course.
    – redsquare
    Aug 4, 2009 at 19:03
  • 1
    He is suggesting to use success instead of complete. 'complete' always fires when the ajax request is 'complete', doesn't matter it completed successfully or unsuccessfully. Aug 4, 2009 at 19:04
  • @redsquare, can you expand on that exactly you disagree with? I was referring to data process and didn't mind any pictures hiding/showing opportunities you have with complete handler . Aug 4, 2009 at 19:07
24

"Chaining" Animation-events with Callbacks.

Suppose you wanted to animate a paragraph vanishing upon clicking it. You also wanted to remove the element from the DOM afterwards. You may think you can simply chain the methods:

$("p").click(function(e) {
  $(this).fadeOut("slow").remove();
});

In this example, .remove() will be called before .fadeOut() has completed, destroying your gradual-fading effect, and simply making the element vanish instantly. Instead, when you want to fire a command only upon finishing the previous, use the callback's:

$("p").click(function(e){
  $(this).fadeOut("slow", function(){
    $(this).remove();
  });
});

The second parameter of .fadeOut() is an anonymous function that will run once the .fadeOut() animation has completed. This makes for a gradual fading, and a subsequent removal of the element.

24

If you bind() the same event multiple times it will fire multiple times . I usually always go unbind('click').bind('click') just to be safe

3
  • 2
    This is not specific to jQuery, though important thing to keep in mind. Aug 4, 2009 at 19:14
  • 11
    You could use live events to not have to bind the same event twice.
    – Powerlord
    Aug 4, 2009 at 19:20
  • live has its own (performance) issues if used to excess. Better in 1.3.3 where you can give context.
    – redsquare
    Aug 4, 2009 at 19:26
23

Don't abuse plug-ins.

Most of the times you'll only need the library and maybe the user interface. If you keep it simple your code will be maintainable in the long run. Not all plug-ins are supported and maintained, actually most are not. If you can mimic the functionality using core elements I strongly recommend it.

Plug-ins are easy to insert in your code, save you some time, but when you'll need an extra something, it is a bad idea to modify them, as you lose the possible updates. The time you save at the start you'll loose later on changing deprecated plug-ins.

Choose the plug-ins you use wisely. Apart from library and user interface, I constantly use $.cookie , $.form, $.validate and thickbox. For the rest I mostly develop my own plug-ins.

3
  • 2
    What about grid? You make your own?
    – jmav
    Oct 28, 2009 at 0:04
  • yes. from project to project data comes in various ways. I prefer to have full control that realizing that grid only helps me to the middle and then I have to improvise. Oct 28, 2009 at 8:49
  • IF{ given enough time, generally i prefer to write all data-driven-dom-manipulation (css/html) code directly. in other words - do not pass data to a 'plugin' and have it spew html. its hard enough to evaluate (the midfield of) plugins for current scope compatibility, forget about the future demands. think... designers, planners, managers, managers, managers. oh and clients and users. but if you have all those things, you will not have enough of said 'time'. so just go use jqgrid already - youre wasting time deliberating. is it done yet?}
    – user406905
    Dec 18, 2010 at 4:33
22

Pitfall: Using loops instead of selectors.

If you find yourself reaching for the jQuery '.each' method to iterate over DOM elements, ask yourself if can use a selector to get the elements instead.

More information on jQuery selectors:
http://docs.jquery.com/Selectors

Pitfall: NOT using a tool like Firebug

Firebug was practically made for this kind of debugging. If you're going to be mucking about in the DOM with Javascript, you need a good tool like Firebug to give you visibility.

More information on Firebug: http://getfirebug.com/

Other great ideas are in this episode of the Polymorphic Podcast: (jQuery Secrets with Dave Ward) http://polymorphicpodcast.com/shows/jquery/

2
  • 1
    I've done the first one many times. You just need to remember that most jQuery functions will operate on all elements returned from a selector. Aug 5, 2009 at 11:38
  • Dislike the .each method to be honest Jan 17, 2013 at 22:11
14

Misunderstanding of using this identifier in the right context. For instance:

$( "#first_element").click( function( event)
{
   $(this).method( ); //referring to first_element
   $(".listOfElements").each( function()
   {
      $(this).someMethod( ); // here 'this' is not referring first_element anymore.
   })
});

And here one of the samples how you can solve it:

$( "#first_element").click( function( event)
{
   $(this).method( ); //referring to first_element
   var $that = this;
   $(".listOfElements").each( function()
   {
      $that.someMethod( ); // here 'that' is referring to first_element still.
   })
});
1
  • 1
    +1 More a javascript problem than a jquery problem, but I used to get tripped up by this a lot.
    – mmacaulay
    Apr 14, 2010 at 16:21
13

Avoid searching through the entire DOM several times. This is something that really can delay your script.

Bad:

$(".aclass").this();
$(".aclass").that();
...

Good:

$(".aclass").this().that();

Bad:

$("#form .text").this();
$("#form .int").that();
$("#form .choice").method();

Good:

$("#form")
    .find(".text").this().end()
    .find(".int").that().end()
    .find(".choice").method();
3
  • 2
    $(".aclass").this().that(); is not good! class only selectors are slow
    – redsquare
    Aug 4, 2009 at 21:24
  • It's an illustrative example showing Jquery's ability to use several methods on one selection. I made the selection simple (and thus slow) to give greater focus on this technique.
    – googletorp
    Aug 5, 2009 at 0:20
  • 11
    While avoiding searching the DOM repeatedly is a good thing — the last example is an unreadable mess where I've got no idea what is going on. If you plan to use the result of a fetch multiple times, store it in a variable. It makes code much more maintainable.
    – Quentin
    Aug 5, 2009 at 11:44
12

Always cache $(this) to a meaningful variable especially in a .each()

Like this

$(selector).each(function () {
    var eachOf_X_loop = $(this); 
})
1
  • 12
    Use $self or $this if you're too lazy to think of a good variable name.
    – gradbot
    May 14, 2011 at 21:15
10

Similar to what Repo Man said, but not quite.

When developing ASP.NET winforms, I often do

$('<%= Label1.ClientID %>');

forgetting the # sign. The correct form is

$('#<%= Label1.ClientID %>');
0
10

Events

$("selector").html($("another-selector").html());

doesn't clone any of the events - you have to rebind them all.

As per JP's comment - clone() does rebind the events if you pass true.

2
  • 4
    Clone() does if you pass true.
    – James
    Aug 6, 2009 at 20:05
  • What about live() in jQuery 1.3.2?
    – jmav
    Oct 28, 2009 at 0:06
9

Avoid multiple creation of the same jQuery objects

//Avoid
function someFunc(){
   $(this).fadeIn();
   $(this).fadeIn();
}

//Cache the obj
function someFunc(){
   var $this = $(this).fadeIn();
   $this.fadeIn();
}
9
  • var $this = $(this).fadeIn();? you're caching an effect?
    – Jason
    Aug 4, 2009 at 20:41
  • 12
    it returns the element, Its called chaining!
    – redsquare
    Aug 4, 2009 at 20:55
  • you can set a variable and perform an action on it at the same time?
    – Jason
    Aug 4, 2009 at 23:00
  • 1
    Indeed, but dont take my word for it. Try it. How do you think the following is possible if the jquery object representing the element is not returned? $('#divId').hide().show().fadeIn()....etc
    – redsquare
    Aug 4, 2009 at 23:07
  • 14
    That works, but I think it's more readable to have $this = $(this); on a separate line. If you can (without making a mess), forget about $this and just chain everything: $(this).fadeIn().fadeIn(); Aug 5, 2009 at 14:40
8

I say this for JavaScript as well, but jQuery, JavaScript should NEVER replace CSS.

Also, make sure the site is usable for someone with JavaScript turned off (not as relevant today as back in the day, but always nice to have a fully usable site).

6

Making too many DOM manipulations. While the .html(), .append(), .prepend(), etc. methods are great, due to the way browsers render and re-render pages, using them too often will cause slowdowns. It's often better to create the html as a string, and to include it into the DOM once, rather than changing the DOM multiple times.

Instead of:

var $parent = $('#parent');
var iterations = 10;

for (var i = 0; i < iterations; i++){
    var $div = $('<div class="foo-' + i + '" />');
    $parent.append($div);
}

Try this:

var $parent = $('#parent');
var iterations = 10;
var html = '';

for (var i = 0; i < iterations; i++){
    html += '<div class="foo-' + i + '"></div>';
}

$parent.append(html);

Or even this ($wrapper is a newly created element that hasn't been injected to the DOM yet. Appending nodes to this wrapper div does not cause slowdowns, and at the end we append $wrapper to $parent, using only one DOM manipulation):

var $parent = $('#parent');
var $wrapper = $('<div class="wrapper" />');
var iterations = 10;

for (var i = 0; i < iterations; i++){
    var $div = $('<div class="foo-' + i + '" />');
    $wrapper.append($div);
}

$parent.append($wrapper);
1
  • +1... I'm using .html() on multiple elements every second. Noticed it does start to slow everything down!
    – User2
    Jun 26, 2014 at 9:16
5

Using ClientID to get the "real" id of the control in ASP.NET projects.

jQuery('#<%=myLabel.ClientID%>');

Also, if you are using jQuery inside SharePoint you must call jQuery.noConflict().

4
  • 11
    ? How is this a pitfall? It's a workaround for ASP.NET behavior. Aug 4, 2009 at 19:16
  • 1
    Yeah. It is nto a jQuery issue. It is a fault of asp.net webforms.
    – redsquare
    Aug 4, 2009 at 19:17
  • 3
    Agreed. But this is something you need to be aware of when using jQuery in ASP.NET regardless. Aug 4, 2009 at 20:37
  • 2
    the OP didn't mention asp.net
    – redsquare
    Aug 4, 2009 at 20:58
4

Passing IDs instead of jQuery objects to functions:

myFunc = function(id) { // wrong!
    var selector = $("#" + id);
    selector.doStuff();
}

myFunc("someId");

Passing a wrapped set is far more flexible:

myFunc = function(elements) {
    elements.doStuff();
}

myFunc($("#someId")); // or myFunc($(".someClass")); etc.
3

Excessive use of chaining.

See this:

this.buttonNext[n ? 'bind' : 'unbind'](this.options.buttonNextEvent, this.funcNext)[n ? 'removeClass' : 'addClass'](this.className('jcarousel-next-disabled')).attr('disabled', n ? false : true);

Explanation

3
  • 1
    It looks funny, it's a sort of obfuscation.
    – Dykam
    Aug 4, 2009 at 19:06
  • 6
    Chaining (on it's own) is difficult to use 'in excess'. It looks like that code makes excessive use of the javascript ternary operator. See en.wikipedia.org/wiki/Ternary_operation#JavaScript for more information. Aug 4, 2009 at 19:43
  • 3
    I'm glad I don't have to maintain your code.
    – cdmckay
    Nov 11, 2009 at 20:14
3

Use strings accumulator-style

Using + operator a new string is created in memory and the concatenated value is assigned to it. Only after this the result is assigned to a variable. To avoid the intermediate variable for concatenation result, you can directly assign the result using += operator. Slow:

a += 'x' + 'y';

Faster:

a += 'x';
a += 'y';

Primitive operations can be faster than function calls

Consider using alternative primitive operation over function calls in performance critical loops and functions. Slow:

var min = Math.min(a, b);
arr.push(val);

Faster:

var min = a < b ? a : b;
arr[arr.length] = val;

Read More at JavaScript Performance Best Practices

1

If you want users to see html entities in their browser, use 'html' instead of 'text' to inject a Unicode string, like:

$('p').html("Your Unicode string")
1

my two cents)

Usually, working with jquery means you don't have to worry about DOM elements actual all the time. You can write something like this - $('div.mine').addClass('someClass').bind('click', function(){alert('lalala')}) - and this code will execute without throwing any errors.

In some cases this is useful, in some cases - not at all, but it is a fact that jquery tends to be, well, empty-matches-friendly. Yet, replaceWith will throw an error if one tries to use it with an element which doesn't belong to the document. I find it rather counter-intuitive.

Another pitfall is, in my opinion, the order of nodes returned by prevAll() method - $('<div><span class="A"/><span class="B"/><span class="C"/><span class="D"/></div>').find('span:last-child').prevAll(). Not a big deal, actually, but we should keep in mind this fact.

0

If you plan to Ajax in lots of data, like say, 1500 rows of a table with 20 columns, then don't even think of using jQuery to insert that data into your HTML. Use plain JavaScript. jQuery will be too slow on slower machines.

Also, half the time jQuery will do things that will cause it to be slower, like trying to parse script tags in the incoming HTML, and deal with browser quirks. If you want fast insertion speed, stick with plain JavaScript.

3
  • 1
    -1 The .html() function is just as fast as the native approach
    – cllpse
    Sep 14, 2009 at 16:15
  • everyone who is downvoting me obviously hasnt tried inserting a ton of DOM on IE and watch things become slow. Reason jquery is slow is it will not simply insert the dom, it does a few other things, like check if the dom has scripts, and executes them if its in IE, and some other stuff that you dont need to do if you know exactly what kind of data you are inserting
    – mkoryak
    Mar 1, 2010 at 16:25
  • 1
    As long as you don't need to worry about browser leaks and such, .innerHTML will do. But if you're building something like Gmail where the user keeps the tab open for hours, you're just going to have to bite the bullet and deal with the extra slowness. For the curious, here's exactly what jQuery's .html() does: james.padolsey.com/jquery/#v=1.4&fn=jQuery.fn.html
    – adamJLev
    Jun 16, 2010 at 5:30
-1

Using jQuery in a small project that can be completed with just a couple of lines of ordinary JavaScript.

8
  • I don't mind being modded down, but please argument your choice.
    – vise
    Aug 31, 2009 at 21:07
  • 8
    -1 jQuery abstracts a broken API. This way you are always sure your code is working. Say you've written some code using jQuery and some random browser-bug gets introduced with a new version--all you need to do is import an updated version of the jQuery framework. Versus having to figure out how to solve the bug yourself.
    – cllpse
    Sep 14, 2009 at 16:17
  • +1 seems reasonable to me - if you're using just a few lines, make sense to just use vanilla JS.
    – alex
    Sep 14, 2009 at 23:41
  • 1
    @roosteronacid, your argument misses the point. It's very unlikely for a browser to introduce a regression in a script of lesser complexity, or dealing with crossbrowser issues for that matter. Two years ago I've working with mootools and under a certain circumstance it was unable to read an elements content on IE. After a few hours of tring to figure out the problem I just rewrote that part with plain js. So, it's actually more likely for jQuery to break rather than plain javascript to fail due to a browser upgrade. I'd solve a bug my self any day rather than hacking through a libraries code.
    – vise
    Sep 15, 2009 at 0:15
  • 3
    couple of lines of ordinary JavaScript Sure no problem. But when is it ever just that? People that say "why not use vanilla javascript??" haven't been bitten hard enough by IE yet... and not to mention how much cruft and boilerplate code you have to write to do simple things in plain old JS.
    – adamJLev
    Jun 16, 2010 at 5:23
-3

Not understanding event binding. JavaScript and jQuery work differently.

By popular demand, an example:

In jQuery:

$("#someLink").click(function(){//do something});

Without jQuery:

<a id="someLink" href="page.html" onClick="SomeClickFunction(this)">Link</a>
<script type="text/javascript">
SomeClickFunction(item){
    //do something
}
</script>

Basically the hooks required for JavaScript are no longer necessary. I.e. use inline markup (onClick, etc) because you can simply use the ID's and classes that a developer would normally leverage for CSS purposes.

3
  • 5
    Care to elaborate? Preferably an example? Aug 4, 2009 at 19:00
  • 7
    Doesn't JavaScript provide addEventListener() and attachEvent() to do this?
    – alex
    Sep 14, 2009 at 23:40
  • 2
    separation of concerns, man. Keep your HTML and JS separate
    – Don
    Oct 29, 2014 at 17:38

Not the answer you're looking for? Browse other questions tagged or ask your own question.