简体   繁体   English

如何减少JavaScript事件

[英]How to minimize javascript events

I need to reduce the number of javascript events on a page of my web application. 我需要减少Web应用程序页面上的javascript事件的数量。 Would it be better to migrate these to a onclick attribute on the HTML element? 将它们迁移到HTML元素上的onclick属性会更好吗?

eg 例如

 <input ... onclick="myJavascript"/> 

as opposed to 相对于

 YAHOO.util.Event.addListener(element, 'click', handleElementClick, eventObject);

The issue is that Javascript events are the most resource intensive code that I see in my Javascript profiler (I have used both Developer tools and Firebug). 问题是Javascript事件是我在Javascript Profiler中看到的最占用资源的代码(我已经使用了Developer工具和Firebug)。 I want to reduce the load, and I am wondering what the best way to do this is. 我想减少负载,我想知道这样做的最佳方法是什么。

The better solution would be to use event delegation, which registers ONE event. 更好的解决方案是使用事件委派,该事件委派一个事件。 You just need to sniff out element to determine if you need to take action. 您只需要嗅探元素即可确定是否需要采取行动。 This is considered the best way to improve the performance of javascript events and not pollute the DOM. 这被认为是改善javascript事件的性能并且不污染DOM的最佳方法。 This way would also work for DOM element added to the page with Ajax, meaning you do not need to rebind events to the new elements: 这种方法也适用于使用Ajax添加到页面的DOM元素,这意味着您无需将事件重新绑定到新元素:

document.onclick = function(e) {
    var event = e || window.event;
    var target = event.target || event.srcElement;

    if (target === myElement) {
        // do something here


}

Generally speaking, you should keep your event code inside of your JavaScript code instead of putting it in your HTML. 一般来说,您应该将事件代码保留在JavaScript代码中,而不是将其放入HTML中。 This allows for much easier debugging in the future because it keeps all of the difference pieces of logic in separate locations; 这样可以使将来的调试更加容易,因为它将所有不同的逻辑部分保留在单独的位置。 it's usually considered desirable to have all structure in the HTML, all presentation in the CSS, and all client-side functionality in the JavaScript. 通常认为在HTML中具有所有结构,在CSS中具有所有表示形式以及在JavaScript中具有所有客户端功能是合乎需要的。 Mixing the different layers isn't necessarily bad, it's usually just an unnecessary complication. 混合不同的层并不一定很糟糕,通常只是不必要的复杂性。

However, in a general sense, the best method is the delegation method, which was posted before I could get around to typing it out. 但是,从一般意义上讲,最好的方法是委托方法,该方法是在我可以键入它之前发布的。

如果您想附加多个处理程序,我认为第二种方法更好,并且有更多选项,取决于您使用的框架

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM