简体   繁体   中英

How to minimize javascript events

I need to reduce the number of javascript events on a page of my web application. Would it be better to migrate these to a onclick attribute on the HTML element?

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). 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. 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:

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. 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. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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