Thursday, July 30, 2009

Selectors, optimizing time and jQuery

When I  learned  to use jQuery, it was necesary to me to understand the several  kinds of selectors to do the same duty.

To confront the problem of to do the init of  a few Datepicker calendars (10 in total ), the first way was to make the follows selector (class selector):

<script>
$(".datepicker").datepicker();
</script>

The problem of this kind of selector is that each time that you do it, the jQuery do a whole search by all DOM. In fact, to do this sentence takes a few seconds.

Searching a solution to this response time GAP, the selector was changed by the follows code (a for with id selector):

<script>
var arrId=new Array("id0","id1","id2","id3","id4","id5","id6","id7","id8","id9");
for (x in arrId) {
$("#"+arrId[x]).datepicker();
}
</script>

Where the arrID var is a array with the id's by each  element to set as a datepicker. The id selector always be faster because uses the feature of a document.getElementById() search. This code just takes arround a second.

No comments: