在循环中附加事件处理程序时有问题的浏览器性能

时间:2016-05-15 10:03:35

标签: javascript jquery javascript-events

创建插件时遇到问题。为变量lastIndex设置新值时出现问题。

width变量需要再次计算,如果用户调整其浏览器的大小。 如果我在圈内附加width事件,则会使麻烦性能。 我想出了创建resize函数来包装所有CODE的想法。因此,当用户调整浏览器大小时,我再次调用此函数。

JS:

closure

这是正确的方法吗?或者还有其他更有效的选择,而不是再次附加所有代码?

提前感谢...

1 个答案:

答案 0 :(得分:1)

首先出现性能问题的原因是,每次调用.on('resize', ...)时,都会注册一个在该事件上运行的函数。因此,在5 resize个事件之后,您每次都会调用5个函数,这就是导致速度减慢的原因。

有两种方法可以解决这个问题:

  1. 只为该事件附加一个处理程序(你最终做了什么);或
  2. 使用.one('resize', ...)事件处理程序注册仅在第一个下一个resize事件时触发的函数。
  3. 用例#1是大多数开发人员使用和推荐的。您创建了一个函数(就像您的onScrollbarY),并且每次.on()事件发生时,您都会使用resize注册该函数。

    案例#2非常罕见,您可能不想使用.one(),除非您只想处理该事件的第一次出现,之后没有。如果您想要处理多个,则必须在事件发生后再次致电.one(),告诉它再次侦听该事件。

    编辑:您可以将代码简化为以下内容:

    
    
    var $window  = $(window),
        width    = $window.innerWidth(), // we know the initial width
        $elLog   = $(".scrollbarYLog"),  // we find the scrollbar element
        onResize = function() {
          width = $window.innerWidth();
        },
        onMouseOver = function() {
          $elLog.html(width);
        };
    
    // register the resize function with the "resize" event
    $window.on("resize", onResize);
    // register the mouseover function with the "mouseover" event on the scrollbar
    $elLog.on("mouseover", onMouseOver);
    
    // there is no need to call onResize(), as we've already set the width variable
    
    
    

相关问题