admin管理员组文章数量:1321426
Is it faster to first check if an element exists, and then bind event handlers, like this:
if( $('.selector').length ) {
$('.selector').on('click',function() {
// Do stuff on click
}
}
or is it better to simply do:
$('.selector').on('click',function() {
// Do stuff on click
}
All this happens on document ready, so the less delay the better.
Is it faster to first check if an element exists, and then bind event handlers, like this:
if( $('.selector').length ) {
$('.selector').on('click',function() {
// Do stuff on click
}
}
or is it better to simply do:
$('.selector').on('click',function() {
// Do stuff on click
}
All this happens on document ready, so the less delay the better.
Share Improve this question asked Feb 24, 2014 at 13:40 NiclasNiclas 1,4021 gold badge12 silver badges25 bronze badges 6 | Show 1 more comment4 Answers
Reset to default 13A better way to write the if check is like this
var elems = $('.selector');
if( elems.length ) {
elems.on('click',function() {
// Do stuff on click
});
}
So let us test this and see what the code tells us http://jsperf.com/speed-when-no-matches
In the end you are talking milliseconds of difference and the non if check is not going to be noticeable when run once. This also does not take into account when there are elements to find, than in that case, there is an extra if check. Will that check matter
So let us look when they find elements http://jsperf.com/speed-when-has-matches
There is really no difference. So if you want to save fractions of a millisecond, do the if. If you want more compact code, than leave it the jQuery way. In the end it does the same thing.
Just use
$('.selector').on('click',function() {
// Do stuff on click
}
If no elements exist with the class selector
, jQuery will simply not bind anything.
$('.selector').on('click',function() { // Do stuff on click }
will bind if element exists otherwise not. So this is faster.
Use the binding directly.
$('selector').on('click',function() {
// Do stuff on click
}
If if there are no elements with the specified selector, it won't do anything - not even post an error, which means that actual check for the element would be doing the same thing twice. I wouldn't call it exactly a check of the existence of an element, but the way this is implemented in jQuery certainly acts that way.
本文标签:
版权声明:本文标题:javascript - In jQuery, is it faster to check if an element exists before trying to bind event handlers? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1739479680a2165086.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
if( $('.selector').length ) { $('.selector').on('click',function() { // Do stuff on click } }
will be much slower because the selector is evaluated twice.... if you cache it I don't think it will make much difference – Arun P Johny Commented Feb 24, 2014 at 13:41