2

我有一个站点,每个页面上都有许多 jQuery 事件处理程序,都在一个大的 .js 文件中。

这意味着对于任何页面,大多数事件处理程序都是针对不存在且根本不会使用的 HTML。

这会影响我的表现吗?

编辑:例如,大多数事件处理程序将执行如下操作:

$(".page").on("click", ".notes .add", function(){ ... });

因为.on()适用于新元素,它是否总是在浪费处理能力,或者只有在 ajax 调用后 DOM 发生变化时才会生效?所以为了进一步澄清我的问题,我想我应该把它分成两部分。

  1. 如果有表演叮当,什么时候会发生?(始终,在任何事件上,仅在 DOM 更改时,仅在加载时)。
  2. 丁足以担心吗?我如何衡量这个?如果有一千个这样的听众,叮当声会以秒、毫秒、微秒来衡量吗?我知道我可以加载页面并查看它的“感觉”,但我想知道我是否在开始之前构建了整个错误!
4

2 回答 2

5

它在很大程度上取决于标记,但总的来说,如果不需要的事件处理程序不被使用,最好删除它们。

jQuery 事件使用 Sizzle 选择引擎附加到元素。这意味着调用$('a').click()仍然必须遍历整个 DOM 来搜索链接。由于您的元素不存在,因此不会绑定任何事件,但这并不妨碍 jQuery 必须搜索目标元素。减少 jQuery 工作量的一种方法是在绑定必要的事件之前测试已知元素的存在,比如表单标签。

if ($('form').size() > 0) { 
   // bind events for form here
}

.on()如果事件使用 , 持久化,情况会变得更糟.delegate(),或者.live()因为它们被设计为绑定到所有元素,包括尚未创建的元素,所以它们会占用更多资源。

于 2012-08-07T00:49:01.460 回答
1

I think it goes without saying that you should only include the JavaScript that you actually need. Any piece of code you don't need is just wasting processing power but whether it has a performance impact really depends on your markup / other code / etc.

Instead of worrying about performance, I would worry about maintainability. Do you really want to have only one large JavaScript file with all the code for all pages of your site? It will get messy eventually.


Regarding: $(".page").on("click", ".notes .add", function(){ ... });. It really depends. The nice thing with event delegation is that it only binds one event handler to manage multiple elements.

Here, it binds the event handler only to .page. But the handler is examining any click event originating from a descendant of .page to see whether the element matches .notes .add. It should be obvious that if there are no .notes .add elements, this is just unnecessary computation.

But if instead the .page element does not even exist, then the event handler won't even be bound, which is ok. jQuery will try to find .page elements and will fail. Depending on the complexity of the selector, this can really have an impact (a class name is not complex though).

于 2012-08-07T09:34:51.457 回答