每次我需要访问一个元素时,是否可以通过不调用jQuery来节省开销?

时间:2017-10-26 12:49:43

标签: javascript jquery html performance

假设我有这段代码:

$('#myBox').css('background', 'grey');
$('#myBox').click( function(e){ console.log( 'Box clicked' ); });
$('#myBox').html(' Just a test text ');

到目前为止,我所知道的是我正在搜索每一行都带有myBox ID的元素。 问题:当我对HTML元素进行多次引用时,我会从变量创建中受益吗?

或者,每次访问变量时,变量是否仍会搜索关联的元素? 例如:

var $myBox = $('#myBox');

$myBox.css('background', 'grey');
$myBox.click( function(e){ console.log( 'Box clicked' ); });
$myBox.html(' Just a test text ');

3 个答案:

答案 0 :(得分:18)

var $myBox = $('#myBox');

效率更高,但'#myBox'动态变化时可能会更糟。如果您保存var $myBox但不是'#myBox'更改,则必须手动重新分配var $myBox,这对于大型应用程序来说真的很麻烦。一般来说,我会说你最好将这种优化保留在一个函数的范围内而不是整个应用程序中。

plunkr中有一个非常简单的例子。更真实的一个是内容根据某些API调用而变化。

答案 1 :(得分:6)

您可以衡量性能,比较执行每个代码所需的毫秒数。我会说使用变量执行具有更好的性能,因为它只是第一次分配jquery元素



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>
&#13;
&#13;
&#13;

答案 2 :(得分:4)

重复使用选择器参考,你的第二种情况,肯定更快。这是一个测试: http://jsperf.com/caching-jquery-selectors 后一种情况,重新定义您的选择器,报告为慢约35%。