Monday, October 10, 2011

jQuery caching

It's really simple to select an element in jQuery:

$('#name');

But if we use this selection more than once in our code, we should cache it:

var name = $('#name');
name.val("Johnson");
name.addClass("inputField");
name.parent().append('<p>Some text here</p>');

Every time we select an element with jQuery, the framework goes through the entire DOM until it founds all the elements that match the selector. In the above example, I cached the jQuery object to a variable called name. Later on my code, I can use this variable to modify my element without searching for it again. So I've just quartered the time spent on selection which means I've given a boost to performance.

If I cache multiple elements (for example: form inputs) I usually use an object literal to group them together. So later on my code, I won't get confused which variable relates to which form.

/* Registration form */
var regForm = {
 'name'  : $('#name'),
 'email'  : $('#email'),
 'address' : $('#address'),
 'phone'  : $('#phone') 
};

var contactForm = {
 'name'  : $('#name'),
 'email'  : $('#email'),
 'subject' : $('#subject'),
 'message' : $('#message') 
};

// ... some other code here

if(regForm.name.val() == "") {
 // do something
}

// ... some other code here

if(contactForm.name.val() == "") {
 // do something
}

1 comment: