我已经通过性能分析工具放置了我的网站,它回来说文档/窗口对象上有太多滚动侦听器.
有没有办法找到我的文档/窗口对象的所有滚动侦听器?
可能有以下几点:
window.scroll.listeners
Run Code Online (Sandbox Code Playgroud)
Jua*_*des 10
如果您只是想找到它们,可以使用chrome dev工具.
复制以下答案:
您可以右键单击目标元素 - >选择"检查元素"向下滚动到开发框架的右侧,底部是"事件监听器".展开树以查看附加到元素的事件.不确定这是否适用于通过冒泡处理的事件(我猜不是)
请参阅如何在Chrome DevTools中查看针对元素触发的事件?
此外,您可以在Chrome中以编程方式执行此操作
getEventListeners(window)
Run Code Online (Sandbox Code Playgroud)
请参阅 /sf/answers/1158136941/和https://developers.google.com/chrome-developer-tools/docs/commandline-api#geteventlistenersobject
使用jQuery,您可以使用:
//Change window, for any other element you want to check. IE: document
$._data(window, "events");
Run Code Online (Sandbox Code Playgroud)
您可以检查附加到元素的所有jquery事件,因此如果有人这样做:
$(window).on("scroll", function(){ console.log("scroll"); });
Run Code Online (Sandbox Code Playgroud)
你会看到这样的事情:
使用普通的javascript,您可以"拦截" addEventListener并attachEvent检查附加到窗口的所有事件侦听器,或者检查该问题的任何元素:
(function(){
function interceptListener(type, element){
if(typeof element[type] == "function"){
element[type] = (function(){
var original = this[type];
this.allListeners = this.allListeners || {};
return function() {
this.allListeners[arguments[0]] = arguments[0] in this.allListeners ? this.allListeners[arguments[0]] + 1 : 1;
return original.apply(this, arguments);
}
}.bind(element))();
}
}
interceptListener("attachEvent", window);
interceptListener("addEventListener", window);
})();
Run Code Online (Sandbox Code Playgroud)
将此代码段放在任何其他脚本之前.
如果要检查是否window.onscroll已设置,则可以在窗口加载时测试是否有任何其他脚本设置它:
if(typeof window.onscroll == "function")
console.log("onscroll function");
Run Code Online (Sandbox Code Playgroud)
或者您可以通过以下方式观看酒店:对象观看polyfill
window.watch("onscroll", function(){
if(typeof this.onscroll == "function")
this.allListeners["onscroll"] = this.allListeners["onscroll"] + 1 : 1;
});
Run Code Online (Sandbox Code Playgroud)
然后,您可以检查窗口附加了多少个侦听器:
console.log(window.allListeners);
Run Code Online (Sandbox Code Playgroud)
注意:正如@JuanMendes所指出的那样:Be aware that this is an internal data structure that is undocumented and should not be modified并且应该仅用于调试.