JQuery 代码中使用的 CSS 类的事件侦听器的性能开销
如果我的标记如下所示:
<button id="button-1" class="nice">
<button id="button-2" class="nice">
<button id="button-3" class="nice">
并且我定义了以下 jQuery:
$(".nice").click(function () {
// something happens
});
建立了多少个事件侦听器? 1 还是 3?
如果我有 1000 个按钮而不是 3 个,我应该改用事件委托吗?
从性能角度来看,如果元素类在标记中包含大量元素,最好不要在这些类上定义 jQuery 调用吗?
从性能角度来看,
If my markup looks like this:
<button id="button-1" class="nice">
<button id="button-2" class="nice">
<button id="button-3" class="nice">
and I define the following jQuery:
$(".nice").click(function () {
// something happens
});
How many event listeners are established? 1 or 3?
If I have 1000 buttons instead of 3, should I use event delegation instead?
Is it best, performance-wise, to not define jQuery calls on classes of elements if those classes contain a large number of elements in the markup?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
1) 3 个事件监听器都指向同一个函数。
2) 这取决于您想要完成的任务
3) 尝试做一些基准测试,看看性能影响在哪里变得明显。 我选择了多达 1000 个元素,然后同时进行动画处理 - 并且(在 FF 中)直到大约 600-700 个元素时,性能影响才明显。 性能当然取决于浏览器和JS引擎。 有些(Chrome)会比其他(IE)更快。 值得一提的是,对于该网站,我使用了与您问题中相同的方法。
1) 3 event listeners all pointing to the same function.
2) That depends on what you're trying to accomplish
3) Try doing some benchmarks, see where the performance hit becomes noticeable. I've had up to 1000 elements being selected then animated at the same time - and (in FF) the performance hit was unnoticeable up until about 600-700 elements. Performance of course depends on browser and JS engine. Some (Chrome) will be faster than others (IE). Its worth mentioning that for that site I used the same method as you have in your question.
1) 3
2) 是的
3) 是的,正如您所说,使用事件委托,在 jQuery 中可以通过 .live 功能。 请注意,太多 .live 函数也会影响性能,因此请考虑本机事件委托。
1) 3
2) Yes
3) Yes, as you have said use event delegation which in jQuery is available through the .live function. Be carefull, too many .live function can also impact performance so do consider native event delegation.
$()
函数返回一个数组,并且click()
应用于其中的所有元素。$()
function returns an array andclick()
is applied to all of the elements therein.完全同意! 您必须向包含所有这些好元素的父元素添加一个事件侦听器。 这将大大提高性能。
Completely agree! You must add an event listener to the parent element containing all those nice elements. That will improve the performance a lot.