Categories
JavaScript JQuery

Cache JQuery Selectors To Improve Performance

JQuery logo text

An easy way to improve jQuery performance is to cache reused jQuery selectors. This prevents jQuery from having to search the entire DOM for each instance the selector is being used.

For example, instead of this:

$(document).ready(function() {
	$('#FName').html('My First Name');
	$("#changeName").click(function() {
		$('#FName').html('My Other First Name');
	});
});

Try this:

$(document).ready(function() {
	var fName = $('#FName');
	fName.html('My First Name');
	$("#changeName").click(function() {
		fName.html('My Other First Name');
	});
});

By the way, jQuery id selector maps to the native JavaScript function document.getElementById().

Short Experiment

I still prefer document.getElementById() over jQuery ID selector, when possible, see the results below:

Cache JQuery Selectors (JSFiddle)