开发者

Which technique is better?

Which technique is better:

<span onclick="dothis();">check</span>
开发者_如何学C

or:

<span class="bla">check</span>
<script type="text/javascript">
    $('.bla').click(function(e) {} );
</script>

Are there any differences according to usability, performance etc.?

Thank you!


The second is better from a code quality standpoint since it is considered to be unobtrusive. I am not certain if either approach has measurable performance benefits.

My advice is to stick to the unobtrusive approach - it will save you a lot of time when you are doing maintenance down the road.


The second is much better. See Unobtrusive JavaScript


Always better to keep your script OUT of the DOM.


Technique 1 is intrusive or obstrusive JavaScript: Your markup is intermixed with your JavaScript calls, which can be really messy and is not a separation of concerns.

Technique 2 is unobstrusive: Your JavaScript is kept separate from the markup, keeping both clean but adds a lot of boilerplate code.

Neither is better, although Technique 2 works better for larger projects for me, but always requires looking in two places and can introduce bugs by changing the markup but not the JavaScript.


You should always try and do the best thing which, for most scripts is to put it in a separate file. If it's a small script, like your example, then it's actually going to be quicker to put it in <script> tags in the document head.

Always steer clear of onClick="" and friends; it makes for messy, sometimes repetitive code and can be hard to maintain/debug.

Another note: if your script is huge (100s of lines), the extra time it takes for the browser to fetch the external file is compensated by the fact the script isn't in the HTML, so it will load the same or faster. For small scripts that won't go beyond say a maximum of 50 lines will be fine in the <head>.


In my opinion, the first approach is easier to debug, it is very clear that dothis() is called when you click on the span; it is harder for the second especially when you put the event handling code into a javascript file. For performance, i think it is tiny, although the first one absolutely have better performance.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜