在jQuery中,尝试绑定事件处理程序之前检查元素是否存在更快吗?

在jQuery中,尝试绑定事件处理程序之前检查元素是否存在更快吗?

问题描述:

首先检查元素是否存在,然后绑定事件处理程序,这样更快吗?

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.

只需使用

$('.selector').on('click',function() {
     // Do stuff on click
}

如果类selector中不存在任何元素,则jQuery将完全不绑定任何内容.

If no elements exist with the class selector, jQuery will simply not bind anything.