Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I save overhead by not calling jQuery every time I need to access an element? [duplicate]

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 ');
like image 957
Luca Rossi Avatar asked Oct 26 '17 12:10

Luca Rossi


People also ask

What does $() do in jQuery?

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.

Is jQuery the last element?

jQuery last() MethodThe last() method returns the last element of the selected elements. Tip: To return the first element, use the first() method.


2 Answers

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.

like image 197
guramidev Avatar answered Sep 28 '22 07:09

guramidev


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>
like image 35
Renzo Calla Avatar answered Sep 28 '22 07:09

Renzo Calla