Let's say I have this block of code:
$('#myBox').css('background', 'grey');
$('#myBox').click( function(e){ console.log( 'Box clicked' ); });
$('#myBox').html(' Just a test text ');
What I know so far is that I'm searching an element with the myBox
ID at every line.
The question: would I benefit from a variable creation when I have multiple references to an HTML element?
Or will the variable still search for the associated element every time I access it? Example:
var $myBox = $('#myBox');
$myBox.css('background', 'grey');
$myBox.click( function(e){ console.log( 'Box clicked' ); });
$myBox.html(' Just a test text ');
When a jQuery object is passed to the $() function, a clone of the object is created. This new jQuery object references the same DOM elements as the initial one.
jQuery last() MethodThe last() method returns the last element of the selected elements. Tip: To return the first element, use the first() method.
var $myBox = $('#myBox');
Is more efficient, but it can be worse when '#myBox'
changes dynamically. If you save var $myBox
but than '#myBox'
changes you will have to manually reassign var $myBox
which is really troublesome for large applications. In general i would say you are better of keeping such optimizations in a scope of one function instead of whole application.
A very simple example is here in plunkr. A more realistic one would be when content changes according to some API call.
You can measure the performance comparing the miliseconds that takes to execute each code.., I would say executing with a variable has a better performance because it assign the jquery element just the first time
var time = new Date().getTime();
$('#myBox').css('background', 'grey');
$('#myBox').click( function(e){ console.log( 'Box clicked' ); });
$('#myBox').html(' Just a test text ');
console.log('Miliseconds without variable',new Date().getTime() - time);
var time2 = new Date().getTime();
var $myBox = $('#myBox2');
$myBox.css('background', 'grey');
$myBox.click( function(e){ console.log( 'Box clicked' ); });
$myBox.html(' Just a second text ');
console.log('Miliseconds with variable',new Date().getTime() - time2);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myBox"></div>
<div id="myBox2"></div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With