【发布时间】:2016-04-26 08:27:23
【问题描述】:
我已经通过性能分析工具对我的网站进行了分析,它返回说文档/窗口对象上的滚动侦听器太多。
有没有办法找到我的文档/窗口对象的所有滚动侦听器?
可能是这样的:
window.scroll.listeners
【问题讨论】:
标签: javascript
我已经通过性能分析工具对我的网站进行了分析,它返回说文档/窗口对象上的滚动侦听器太多。
有没有办法找到我的文档/窗口对象的所有滚动侦听器?
可能是这样的:
window.scroll.listeners
【问题讨论】:
标签: javascript
使用jQuery,你可以使用:
//Change window, for any other element you want to check. IE: document
$._data(window, "events");
您可以检查 所有 jquery 事件附加到一个元素,所以如果有人这样做:
$(window).on("scroll", function(){ console.log("scroll"); });
你会看到这样的东西:
使用纯 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);
})();
将此 sn-p 放在任何其他脚本之前。
如果您想检查是否设置了window.onscroll,您可以测试是否有其他脚本设置了窗口加载:
if(typeof window.onscroll == "function")
console.log("onscroll function");
或者您可以通过object watch polyfill查看房产
window.watch("onscroll", function(){
if(typeof this.onscroll == "function")
this.allListeners["onscroll"] = this.allListeners["onscroll"] + 1 : 1;
});
然后你可以检查有多少监听器附加到窗口:
console.log(window.allListeners);
注意: 正如@JuanMendes 指出的那样:Be aware that this is an internal data structure that is undocumented and should not be modified 并且只能用于调试。
【讨论】:
but be aware that this is an internal data structure that is undocumented and should not be modifiedblog.jquery.com/2011/11/08/building-a-slimmer-jquery
window.onscroll。一半答案的问题是其他人来到 StackOverflow 期望标记为已接受的答案是正确的。我们一直在努力回答问题并帮助所有其他用户,而不仅仅是提出问题的用户。
如果你只是想找到它们,你可以使用 chrome 开发工具。
从下面的答案复制:
您可以右键单击目标元素->选择“检查元素”在开发框架的右侧向下滚动,底部是“事件侦听器”。展开树以查看附加到元素的事件。不确定这是否适用于通过冒泡处理的事件(我猜不是)
见How do I view events fired on an element in Chrome DevTools?
此外,您可以在 Chrome 中以编程方式进行操作
getEventListeners(window)
见https://stackoverflow.com/a/16544813/227299和https://developers.google.com/chrome-developer-tools/docs/commandline-api#geteventlistenersobject
【讨论】: