Scooter Daraf
Scooter Daraf

Reputation: 535

Optimise jquery selectors

i have read that some selectors can be obtimised to use querySelectorAll(). and this is an example.

$('a.button:animated'); // Does not use querySelectorAll()
$('a.button').filter(':animated');  // Uses it and faster.

and i have this selector :

 $( 'input[name="annoncedby"]:radio' ).on('change',function(){
   ....
 }

i used it like that :

  $( 'input[name="annoncedby"]').filter(':radio' ).on('change',function(){
   ....
   }

But its not fast , how can this be done to be faster thanks?

Upvotes: 0

Views: 73

Answers (2)

iCollect.it Ltd
iCollect.it Ltd

Reputation: 93561

An alternative approach would be to use a delegated event handler, attached to an ancestor of all the radio buttons.

This will provide much faster initial event hookup and no noticeable decrease in speed at event time:

$('#someparentid').on('change', 'input[name="annoncedby"]:radio', function(){
   ....
});

It works by applying a single event handler, which listens for the change event to bubble up to the ancestor element, then applies the jQuery selector to the elements in the bubble-chain, then applies the function to any matching elements that caused the event. As the event response is only at user-interface speeds, there is no real down-side to using this approach.

To give you an idea of the speed difference of event registration, I have updated the JSPerf test from @Musa. The only addition to the HTML was a parent element to connect the handler to.

JSPerf: http://jsperf.com/queryselectorvssizzle/2

Upvotes: 1

code_monk
code_monk

Reputation: 10120

The idea behind those optimisations is that sizzle will not be needed if standards-based query selectors are used, and if you need to use a sizzle-only selector, you add it in it's own clause, and JQuery is smart enough to make the optimisations.

This code circumvents JQuery altogether, ensuring maximum performance:

"use strict";

//  various ways to select the element
var radios = document.querySelectorAll('[name="annoncedby"]');
//var radios = document.querySelectorAll('input[name="annoncedby"]');
//var radios = document.querySelectorAll('input[name="annoncedby"][type="radio"]');

for (var i in radios) {
  radios[i].addEventListener('change',function(event){
    alert( this.value );
  });  
}
<form>
  <input type="radio" name="annoncedby" value="daryl" />  
  <input type="radio" name="annoncedby" value="pete" />
</form>

Upvotes: 1

Related Questions