开发者

Inline javascript performance

开发者 https://www.devze.com 2022-12-22 02:53 出处:网络
I know it is better coding practice to avoid inline javascript like: <img id=\"the_image\" onclick=\"do_this(true);return false;\"/>

I know it is better coding practice to avoid inline javascript like:

<img id="the_image" onclick="do_this(true);return false;"/>

I am thinking about switching this kind of stuff for bound jquery click events like:

$("#the_image").bind("click",function(){
     do_this(true);
     return false;
});

Will I lose any performance if I bind a ton of click events? I am not worried about the time it takes to initially bind the events, but the response times between clicking and it happening.

I bet if there is a difference, it is negligible, but I will have a ton of functions bound. I'm开发者_JAVA技巧 wondering if browsers treat the onclick attribute the same way as a bound event.

Thanks


Save yourself the worry, use the on event

$("#the_image").on("click",function(){
     do_this(true);
     return false;
});

One event, with no performance hit with multiple items.


In my work, it depended. I moved all of my events to jquery. Then I profiled the javascript using FireBug to see what was taking the longest. Then I optimized those taking the longest.

If its just a few, you won't notice any degradation. If its hundreds or thousands, then you might.


The difference is negligible. If you have to bind to many items in the page, there can be a performance hit, and you may want to bind to a higher level object, and simply intercept the target item (image) where you are binding the click to a containing DIV tag. Other than that, it should be fine and will depend on your use case specifically.

Look into event bubbling in javascript for more specifics.

0

精彩评论

暂无评论...
验证码 换一张
取 消