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

Luc*_*ssi 18 html javascript performance jquery

假设我有这段代码:

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

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

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

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

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

gur*_*dev 17

var $myBox = $('#myBox');
Run Code Online (Sandbox Code Playgroud)

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

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


Ren*_*lla 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);
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myBox"></div>
<div id="myBox2"></div>
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

1322 次

最近记录:

7 年,10 月 前