koket
koket

Reputation: 13

Which technique is better?

Which technique is better:

<span onclick="dothis();">check</span>

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!

Upvotes: 1

Views: 124

Answers (6)

Michael Stum
Michael Stum

Reputation: 180944

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.

Upvotes: 1

Bojangles
Bojangles

Reputation: 101493

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

Upvotes: 0

James.Xu
James.Xu

Reputation: 8295

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.

Upvotes: -2

SeanCannon
SeanCannon

Reputation: 77966

Always better to keep your script OUT of the DOM.

Upvotes: 1

david
david

Reputation: 471

The second is much better. See Unobtrusive JavaScript

Upvotes: 1

Andrew Hare
Andrew Hare

Reputation: 351516

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.

Upvotes: 8

Related Questions