55

A knowledgeable friend recently looked at a website I helped launch, and commented something like "very cool site, shame about the inline scripting in the source code".

I'm definitely in a position to remove the inline scripting where it occurs; I'm vaguely aware that it's "a bad thing". My question is: what are the real problems with inline scripting? Is there a significant performance issue, or is it mostly just a matter of good style? Can I justify immediate action on the inline scripting front to my superiors, when there are other things to work on that might have a more obvious impact on the site? If you pulled up to a website, and took a peek at the source code, what factors would lead you to say "hmm, professional work here", and what would cause you to recoil from an obviously amateurish job?

Okay, that question turned into multiple questions in the writing. But basically, inline scripting - what's the deal?

5
  • 3
    Reuse and separating design from implementation are two reasons not to inline off the top of my head. Jun 23, 2011 at 19:39
  • 1
    Missing some context here - what do you mean by "inline scripting?"
    – greyfade
    Jun 23, 2011 at 19:39
  • Yeah, is it CSS inside the page, JS in the page, or something else?
    – Michael K
    Jun 23, 2011 at 19:40
  • 2
    @greyfade, Michael: Well, my friend didn't specify, so let's assume it's both. Let's say more JS, as that's usually closer to my area of responsibility... Jun 23, 2011 at 19:45
  • 2
    Unless you are creating redundant code I do not see a problem with it. Though if you have a large amount of code inline it might look inelligant. But I just use Confirms inline rather than writing a function in a script block to call. Jun 23, 2011 at 19:51

10 Answers 10

38

what are the real problems with inline scripting? Is there a significant performance issue, or is it mostly just a matter of good style?

The advantages are not performance based, they are (as Michael pointed out in his comment) more to do with separation of the view and the controller. The HTML/CSS file should, ideally, contain only the presentation and separate files should be used for scripts. That makes it easier for you (and your peers) to read and maintain both the visual and functional aspects.

Can I justify immediate action on the inline scripting front to my superiors, when there are other things to work on that might have a more obvious impact on the site?

No, probably not. It can be very hard to convince the powers that be of pure maintenance work, even if it you believe it will save them money in the long run. In this case though, I don't think it is so important that you should stop everything and get rid of your inline scripting. Instead, just make sure that you make a conscious effort to rectify areas as you work on them for other reasons. Refactoring code should be something you do regularly but only a little bit at a time.

If you pulled up to a website, and took a peek at the source code, what factors would lead you to say "hmm, professional work here", and what would cause you to recoil from an obviously amateurish job?

The number one factor that would tell me it is not professional is the overuse of tables or divs. Here is an article explaining why neither should be overused.

3
  • "No, probably not." I mean, how much work is it really to copy code into a JS file and then src="" it? I guess it depends on how big and complicated the site is, I know that some websites get way out of hand. I generally take the "sometimes it's better to just do it and then explain it later" approach if it's more on the trivial side though.
    – Andrew
    Jul 1, 2020 at 15:18
  • 2
    @Andrew Looking at this answer after quite a few years I actually don't really agree with it. A lot of 'shoulds'. Not really an answer that shows my experience, it just shows I can read and follow what other people say. I agree with what you're saying, that's how I do it. Just as a matter of course I refactor things to a better structure. I usually only do that for the specific area I'm working on though and little by little the code will improve. Asking for a specific time to be set aside for refactoring is what can be a hard sell sometimes. Jul 8, 2020 at 10:38
  • That's why you don't ask. ;) Just make sure the time you allot to it is reasonable and you can justify it...
    – Andrew
    Jul 9, 2020 at 10:28
53

I'm not going to be the devil's advocate, but there is no strict relationship between amateurish job and inline JavaScript. Let's see the source code of several most known websites:

  • Google,
  • Wikipedia,
  • Microsoft,
  • Adobe,
  • Dell,
  • IBM.

Every of their home pages use inline JavaScript. Does it mean that all those companies hire amateurish people to create their homepages?


I'm one of those developers who can't put JavaScript code inside HTML. I never do it inside the projects I work on (except probably some calls like <a href="javascript:..."> for the projects where unobtrusive JavaScript was not a requirement from the beginning, and I always remove inline JavaScript when I refactor code of somebody else. But does it worth the effort? Not so sure.

Performance-wise, you don't always have better performances when putting JavaScript in a separate file. Usually, we are tempted to consider that inline JavaScript waste bandwidth, since it cannot be cached (except when you deal with static cacheable HTML). On the opposite, an extern .js file is loaded only once.

In reality, this is just another premature optimization: you may be right thinking that externalizing JavaScript would fasten your website, but you may also be totally wrong:

  • What if most of your users come with an empty cache?
  • Do you considered that with an extern .js file, a request will be made to this file at every page request, if the website is not configured properly (and usually, it's not),
  • Is .js file really cached (with IIS, it may not be so easy)?

So before optimizing prematurely, collect statistics about your visitors, and evaluate the performances with and without inline JavaScript.

Then comes the final argument: you mixed JavaScript and HTML in your source, so you suck. But who said you mixed both? The source code used by the browser is not always the source code you wrote. For example, the source code may be compressed, minified, or several CSS or JS files may be joined into one file, but this doesn't mean that you really named your variables a, b, c ... a1, etc. or that you wrote a huge CSS file without spaces or newlines. In the same way, you can easily have external JavaScript source code injected into HTML at compile time or later through the templates.


To conclude, if you mix JavaScript and HTML in the source code you write, you should consider not doing it in your future projects. But it doesn't mean that if the source code sent to the browser contains inline JavaScript, it's always bad.

  • It may be bad.
  • It may on the opposite be a sign that the website was written by professionals who cared about performance, made specific tests, and determined that it would be faster for their clients to inline parts of JavaScript.
  • Or it may not mean anything at all.

so rather shame on the person who says "very cool site, shame about the inline scripting in the source code" by looking just at the source sent to the browser, without knowing anything about how the website was done.

2
  • 2
    +1 for doing research and being thoughtful. The reality is there are build tools that can make code developed in separated files be composited to inline after the fact. HTML+CSS+JS is the assembly language of the web. The way things are delivered (minified, composited) can have nothing to do with how they are made.
    – Evan Moran
    Feb 2, 2013 at 16:26
  • can I ask why React encourages you to use inline javascript? I think they are totally wrong because ppl uses it on big projects Aug 11, 2021 at 13:40
25

It's generally good to try to keep HTML and JS generally separated. HTML is for the view, JS is for the application logic. But in my experience extreme decoupling of html and javascript (for the sake of purity) does not make it more maintainable; it can actually be less maintainable.

For example, I sometimes use this pattern (borrowed from ASP.net) in setting up event handlers:

<input type="button" id="yourId" onclick="clickYourId()" />

or

<input type="button" id="yourId" onclick="clickYourId(this)" />

There's no mystery what is triggering an event to happen. The reason is that six months later you can inspect the element (eg, in Chrome) and see immediately what javascript event is triggered.

On the other hand, imagine you are reading someone's else's code, which is a hundred thousand lines, and you come across a magical element that fires off a javascript event:

<input id="yourId"  />

How can you easily tell me what javascript method this is calling? Chrome has made this easier, but perhaps the event is bound to the id, or perhaps it's bound to the first child of the container. Maybe the event is attached to the parent object. Who knows? Good luck finding it. :)

Also, I would argue that hiding javascript completely from the designer may actually increase the likelihood of them breaking it on an update. If someone edits code for an magically active element, what indication in the code do they have that would let them know this is an active element on the page?

So in short, best practice is to separate HTML and Javascript. But also understand rules of thumb are sometimes counterproductive when carried to the extreme. I'd argue for a middle-road approach. Avoid large amounts of inline js. If you do use inline, the function signature should be very simple like:

1. emptyFunction()
2. doCallWithThis(this)
3. atTheExtremOnlyPassOneNumber(2)
3
  • 3
    Good point! Great answer.
    – Julian
    May 6, 2014 at 9:22
  • 2
    Indeed, great answer. As long as JS makes it so hard to find to find attached listeners, inline scripting will continue to be easier to maintain.
    – JohnK
    May 12, 2015 at 21:34
  • 1
    This is the best answer in my opinion. Anything to the extreme is often "over doing" it.
    – deebs
    Sep 24, 2015 at 14:05
17

One argument I'm missing here is the possibility of increased protection against cross site scripting attacks.

It's possible to disable the execution of inline JavaScript in modern browser via the Content Security Policy. This reduced the risk of your site falling victim of XSS. This may be a more convincing argument to make to your management to invest in removing inline script.

5
  • 3
    I think it's the best answer now.
    – Supersharp
    Jan 8, 2016 at 22:56
  • 4
    This deserves much more upvotes and attention, in my humble opinion. May 25, 2017 at 17:36
  • Valid Point !!!
    – Anshul
    Sep 9, 2018 at 19:40
  • This is not the case when the inline script is static, right? Aug 17, 2019 at 18:27
  • 1
    Just to spell this out: you hopefully already have ways of sanitizing user input, so that a user can't (eg) type in a comment that includes JavaScript and get that comment rendered on the page as executable JavaScript, which then runs in the browser of every other visitor. But by prohibiting inline JS with a Content Security Policy, you're telling visitors' browsers - "hey, if by some chance we mess up and somebody manages to slip their own JS into the page, don't execute it. We only intend to load JS from the following sources." See content-security-policy.com/unsafe-inline Jun 24, 2020 at 13:45
9

Here's a few reasons.

  1. Inline script cannot be minified (converted to a shorter version through symbol reduction). Not a concern on broadband but consider a mobile device in a low bandwidth area, or users who are on global data roaming-- every byte may count.

  2. Inline script cannot be cached by the browser unless the page itself is cacheable (which would make for a very dull page). External Javascript files need only be retrieved once, even if the page content changes every time. Can seriously affect performance on low bandwidth connections.

  3. Inline script is harder to debug because the line number associated with any error is meaningless.

  4. Inline script is reputed to interfere with accessibility (508/WAI) considerations, although that does not mean all inline script causes issues. If you end up with a screen reader announcing script content you have a problem! (Never seen this happen though).

  5. Inline script cannot be tested independently of its page; external Javascript files can be run through independent testing, including automated tests.

  6. Inline script can lead to poor separation of concerns (as described by many of the other answers here).

1
  • 2
    Some pages can be static and yet of value--earlier today I was using a page with a calculator on it. Cacheable, yet useful. I do agree non-trivial Javascript doesn't belong on any dynamic page. May 8, 2015 at 2:56
3

There are multiple reasons that would justify not including the script inline:

  • First of all, the obvious answer- it makes for code that is cleaner, more concise, easier to understand and read.

  • From a more practical standpoint, you often want to reuse scripts/CSS/etc. all over your website- inlining these parts would mean having to edit every single page every time you do a small change.

  • If you use a SCM for your project, then having your different components well separated will make tracking changes and commits easier for everyone involved.

As far as I know, performance would not be a concern. It would depend on a lot of things related to the nature of your website, the specs of your server, etc. For instance, if your webpage uses a lot of javascript, your browser may cache the scripts, which would result in better performance when the code is separated in multiple files. On the other hand, I'd be tempted to say that some servers might serve a single large file faster than multiple smaller files- in this case one could argue that not separating the code is better performance wise.

I'm not aware of any formal tests in this area, although it's very likely someone has done them.

In the end, I would say that it's a matter of good practices more than anything else, and that the advantages in terms of readability and organization (specifically w.r.t. point 2) make separating the code in distinct files a much better option.

2
  • It's possible to download external files asynchronously, either so that it's cached for a later page while the visitor is reading or to allow the page, images, etc to download while the script is downloading - so there can be performance gains if these techniques are being used (download times not execution speed).
    – FinnNk
    Jun 23, 2011 at 20:39
  • 1
    Pointing out a problem with this post: "obvious answer- it makes for code that is cleaner, more concise, easier to understand and read." This, to me, is "obviously" false when it comes to finding out what a button does while glancing at the HTML.
    – wtr
    Jul 4, 2021 at 3:59
3

The answer really depends on how the in-line code (assuming javascript) is used.

We used a combination of inline code, SSI's (server side includes), js files and css files to create the effects we wanted and to also reduce server return trips for onClick events.

So for someone to make a blanket statement that the use of "in-line code" is bad without fully understanding how it's used can be misleading.

Having said that, if each page has the same copy and pasted javascript code instead of using a js file I say that's bad.

If each page has it's own copy and pasted CCS section instead of using a css file I say that's bad.

It's also a lot of overhead to include your entire js library on every page, especially if none of the functions are being used on that page.

1

I'm going to assume inline javascript here.

Without seeing the code, it's hard to be sure. I suspect he was refering to either of two things:

  1. You have <script>s scattered throughout the page
  2. All you JS is in the header of the page, not in external files

The first is a bad design decision. Spreading scripts throughout a source file makes the page much harder to maintain, because you have to search for a given script. It's much better to keep all that code in one place (I prefer at the top of the source file).

As for the second - that's not necessarily a bad thing. Page specific code should be in that page. If you have duplicate code between pages, you should externalize it using <script src>. Then when you go to create a new page, you can simply include that file and any bugs you fixed there won't have to be revisited.

2
  • 1
    Note that scripts block other things from downloading, it's generally better to put them at the bottom of the page (although sometimes you will want them to block, in which case they belong in the head). CSS, which can download in parallel is better at the top, above any script references.
    – FinnNk
    Jun 23, 2011 at 20:37
  • 1
    Disagree here. A better design for page specific javascript (not the only one) is to have page specific javascript in a separate .js file that is only included on that page. That way, the file will benefit from caching, can be minified, etc. Feb 23, 2012 at 3:32
1

One reason NOT to use InLine Javascript (not even onclick="DoThis(this)" on buttons), is if you intend to make your web application a Chrome App. So, if you are planning to port your web app into a Native Chrome App, start by NOT including ANY inline javascript. This is explained right at the beginning of what you will need to change (mandatorily) from your web app if you intend to "Chrome-etize" it.

0

What are the real problems with inline scripting?

Inline scripting is bad and should be avoided because it makes the code more difficult to read.

Code that is difficult to read is difficult to maintain. If you can't easily read it and understand what's going on, you won't be able to easily spot bugs. If it's difficult to maintain, it will waste more of your time later when there are problems.

The difficulty usually comes from nested encodings. There is a problem in the next line of code, can you spot it?

<a onclick='alert("What\'s going wrong here?")'>Alert!</a>

Ideally code is written in a way that makes it easy to spot when there's a mistake. Joel Spolsky wrote a great article that emphasizes this point back in 2005. The code examples could use some significant improvement, as they're showing their age being 9 years old, but the underlying concept still stands strong: write code in a way that makes it easy to pick out bugs.

Is there a significant performance issue, or is it mostly just a matter of good style?

Inline scripting leads to repetition. Instead of changing one line of code to affect 100 pages, you'll likely need to change 100 pages individually. This along with poor readability seriously affect performance of the maintainer. Programming time has a real cost that affect the bottom line of a business faster than the few milliseconds from most code optimizations. Certainly optimizing bottlenecks is important, but the performance difference of the code is negligible in this case.

Can I justify immediate action on the inline scripting front to my superiors, when there are other things to work on that might have a more obvious impact on the site?

No. If it's stupid and it works, it isn't stupid.

The programming corollary to this is: if it's stupid code and it works, it isn't stupid code. Focus on the real issues before trying to fix something that isn't broken. When the inline code eventually needs an update, whether that's in six hours, six months, or six years, fix the code in a way that makes future maintenance on it easier.

What factors would lead you to say "hmm, professional work here", and what would cause you to recoil from an obviously amateurish job?

I tend to prefer to define "professional" merely as someone who is paid to perform a task, rather than assume that they possess any significant ability in what they're being paid to do. Many professionals are certainly capable of performing good work, but more often than not I find myself recoiling in horror at the terrible job that other professionals have done rather than something that an amateur has come up with. Much of my work to date has involved salvaging train-wreck projects that were botched by the initial developers, so your mileage may vary.

With all that said, it's generally easy to pick out enterprise quality programming

Not the answer you're looking for? Browse other questions tagged or ask your own question.