Pergunta

What are downside and advantage of method chaining in jQuery ?

Is it faster than re-declaring selector?

Foi útil?

Solução

Most probably the advantages are,

that It makes your code short and easy to manage.It gives better performance(faster). And the chain starts from left to right. So left most will be called first and so on.

When chaining is used JQuery has to find the elements once and it will execute all the attached functions one by one.

An disadvantage of chaining can be using it unnecessarily too much then it can cause performance degrading.

eg:- Code 1:

​$(document).ready(function(){
    $('#myContent').addClass('hello');
    $('#myContent').css('color', 'blue');
    $('#myContent').fadeOut('fast');
});​

Code 2:

$(document).ready(function(){
    $('#myContent').addClass('hello')
          .css('color', 'blue')
          .fadeOut('fast');     
});​

Both these code does the same thing. and the Code 2 uses chaining and it is faster and shorter in code. And in Code 1 JQuery has to search the entire DOM to find the element and after that it executes the function on it.

Outras dicas

Advantages of method chaining:

  1. Selector is only evaluated once for multiple operations. Better performance, smaller code.
  2. Selector result can be used for multiple methods without having to assign it to a local variable. More compact code.
  3. Multiple methods can more compactly be put on one line.
  4. A lot more compact specifically when you want operations on consecutive different results such as $(this).next().find("span.title").closest(".section").hide();. Without chaining, you would need four different local variables where this needs none.

Disadvantages of chaining:

  1. The selector result has not been saved in a local variable for more complicated uses that can't be done only with chaining.
  2. Cramming too many consecutive chained methods on one line can compromise code readability if it extends to make a very long line of code. (One can still use chaining, but just insert occasional linebreaks in the chaining to avoid this).

Yes, it can be faster but not when compared with storing the jQuery object in a variable, which is just as fast.

e.g. this:

var elements = $('.myClass').find('p');
elements.next()

should be just as fast as this:

$('.myClass').find('p').next()

Most of the time it comes down to readability...sometimes method chaining makes code more readable, but if you get carried away, it can make it less readable.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top