Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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?

share|improve this question
3  
Reuse and separating design from implementation are two reasons not to inline off the top of my head. –  Michael Todd Jun 23 '11 at 19:39
1  
Missing some context here - what do you mean by "inline scripting?" –  greyfade Jun 23 '11 at 19:39
    
Yeah, is it CSS inside the page, JS in the page, or something else? –  Michael K Jun 23 '11 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... –  thesunneversets Jun 23 '11 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. –  Chad Jun 23 '11 at 19:51

8 Answers 8

up vote 17 down vote accepted

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.

share|improve this answer

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.

share|improve this answer
    
+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 '13 at 16:26

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.

share|improve this answer
    
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 '11 at 20:39

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.

share|improve this answer

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)
share|improve this answer
1  
Good point! Great answer. –  Julian May 6 at 9:22

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.

share|improve this answer
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 '11 at 20:37
    
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. –  SamStephens Feb 23 '12 at 3:32

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

share|improve this answer

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

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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