javascript - 在循环内附加事件处理程序时浏览器性能出现问题

标签 javascript jquery jquery-events

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

如果用户调整浏览器的大小,

width变量需要再次计算。 如果我在循环内附加resize事件,则会导致性能出现问题。 我想出了创建闭包函数来包装所有代码的想法。因此,当用户调整浏览器大小时,我会再次调用此函数。

JS:

var self         = this,
    onScrollbarY = function() {
        self.each(function() {  // loop it
            var el           = $(this),
                elLog        = el.find(".scrollbarYLog"),
                width        = $(window).innerWidth(),    // this value will change based on users browser width
                onMouseOver  = function() {
                    elLog.html(width);
                };
            elLog.on("mouseover", onMouseOver);
        });
    };
onScrollbarY(); // call it immediatly

$(window).on("resize", onScrollbarY); // if users resize its browser, call it again for getting new browser width

这是完成它的正确方法吗?或者还有其他比再次附加所有代码更有效的选项?

最佳答案

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

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

  1. 仅将一个处理程序附加到该事件(您最终执行的操作);或
  2. 使用.one('resize', ...)事件处理程序来注册一个仅在下一个 resize 事件时触发的函数。

用例 #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

关于javascript - 在循环内附加事件处理程序时浏览器性能出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37236930/

相关文章:

c# - 将变量从 VB 函数传递到客户端 javascript

javascript - 在javascript中将数组导出到excel xlsx

javascript - 最初的 promise 成功后又拒绝内心的 promise ?

javascript - 如何使用javascript在excel应用程序中打开excel html文件

javascript - 防止在页面加载时点击链接

jquery - 使用 jQuery 重新绑定(bind) DOM 事件

javascript - jQuery.click() 与 onClick

asp.net - 如何在 asp.net 中执行 Javascript 重定向

javascript - IE9 事件是否完全符合 DOM Level 2 标准?

javascript - 未捕获的类型错误 : Cannot read property 'call' of undefined on jQuery Validation