【问题标题】:high latency on event with jqueryjQuery 事件的高延迟
【发布时间】:2015-01-17 23:54:13
【问题描述】:

我的 webapp 非常慢,我开始调查以找出原因。我想我找到了问题,但没有找到解决方案。 我用控制台分析,你可以在屏幕上看到结果。问题是每次我点击时,由于点击事件,延迟将近 1000 毫秒。首先,我认为这是因为我的代码中有太多的事件点击主体,但正如你所看到的,如果总成本只有 0.3% 到 1% 之间),与 n.event.handler 的 97.71% 相比非常小. 所以我的问题是这种延迟是从哪里来的?

在我的代码中,有很多:

 $('html').on('click', '.class', function(){ });

可能太多了?

【问题讨论】:

  • 如果没有看到在该点击处理程序中运行的代码,我们怎么可能回答这个问题?
  • 试试$(document).on('click', '.class', function() {})。它可能无法解决您的问题,but it's seemingly faster
  • @DanLee 您正在测试事件处理程序的附件,而不是调用。
  • 你的代码中有多少? 10s? 100 多岁? 1000s?
  • 我认为 1000s 比 100s 最接近

标签: jquery performance events latency


【解决方案1】:

如果你认为你有太多这些:

$('html').on('click', '.class', function(){ });

您可以尝试将它们重构为一个处理程序:

$('html').on('click', function (e) {

  if (e.target.classList.contains('class')) {
       // e.target is the clicked element
      // do something here
  }

  if ($(e.target).is('class2')) {
     // you can wrap e.target into a jQuery object
     // the same way you wrap this.
     // do something else here
  }

});

另外,根据对this question 的回答,如果您有大量动态创建的目标,您应该删除并重新添加这些事件处理程序。

【讨论】:

  • 谢谢你,但在这种情况下,我怎样才能从点击中获得 $('this')?
  • "this.classList.contains('class')",不行,找不到类。使用你在它工作之前编写的 e 目标,但在我的函数中我使用 $(this),它对我来说真的很有用。
  • Aw cr*p,之前是正确的。 $(e.target) 然后等于你之前使用的 $(this)
猜你喜欢
  • 2011-01-17
  • 2012-07-11
  • 2010-09-30
  • 1970-01-01
  • 2013-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-15
相关资源
最近更新 更多