19

Is it bad to use inline JavaScript event handlers, or is that fine?

On the page I plan to use it on, I'm only going to use an event handler once, so is it acceptable to use an inline event handler in this case, or shall I write the code for the event handler within <script> tags?

Sharikul Islam
  • 319
  • 2
  • 8
  • 3
    Writing javascript event handlers inline is a good practice for who? Only use javascript inline when you absolutely need it, that makes your code really ugly and hard to maintain. Always put all your javascript into separated files and include in your html . – Rodrigo Dias Apr 03 '13 at 16:15
  • I'm personally a fan of [unobtrusive javascript](http://en.wikipedia.org/wiki/Unobtrusive_JavaScript). It can be done either way. The question is should it be done inline. I would argue no. – War10ck Apr 03 '13 at 16:18
  • 2
    HTML belongs in `.html` files, CSS belongs in `.css` files, JS belongs in `.js` files. – zzzzBov Apr 03 '13 at 18:31
  • 1
    knockout js seems to follow this pattern with great success. What I do is I put all my code in separate js files and then just call functions for events. – Akshat Jiwan Sharma Dec 29 '13 at 05:47
  • Yes as of 2022 it's blocked by CSP https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src – Alexred Oct 19 '22 at 20:25

1 Answers1

13

Its bad practice if your concern is readability in your mark-up and maintenance, especially on a larger scale it can get quite messy - also keep in mind the inline JS will never be cached like an external js file would so you do suffer a bit in regards to performance especially if you abuse it

Read this article for more insight: http://robertnyman.com/2008/11/20/why-inline-css-and-javascript-code-is-such-a-bad-thing/

Adrift
  • 58,167
  • 12
  • 92
  • 90
  • 1
    I thought the html (inline js) would get cached as well. Is that not correct? – papiro May 24 '17 at 10:34
  • 1
    @papiro: It will only be cached if you employ some sort of caching of your html (by the server). This is typically not by default. External js _is_ usually cached by default (by the browser). – Protector one Apr 20 '18 at 10:36
  • Though, if inline-js was such a bad thing and we shall always try to avoid it, why were they introduced at first place? – RegarBoy Oct 30 '21 at 09:01