Why inline CSS and JavaScript code is such a bad thing

Published on Thursday, November 20th, 2008

When I review web sites, and also in my own projects with a number of different team members, I almost constantly stumble across something web developers should really refrain from: inline styling and inline JavaScript code.

What is inline style and inline JavaScript?

Let’s begin with explaining what I mean with having CSS and JavaScript inline: it is when you integrate your HTML code directly with either of them, resulting in having presentation and interaction code spread all throughout the page. Like this:

<div style="width: 800px; margin: 1em auto; font: bold 1em/1.2 Verdana, Arial, Helvetica, sans-serif">
    <div style="float: left; width: 400px; padding: 1em 2em; font-size: 0.9em">
        <span id="get-shit" onclick="callSomeFunction()">News</span>
    </div>
</div>

What is so bad with it?

Except for not being very pretty code, and hard to get a good overview of it, there are some real disadvantages to this:

HTML file size
Your HTML code will weigh more, i.e. a web page riddled with similar code will have a KB size that is a lot larger than necessary.
Lack of caching
HTML code will never be cached. Contrary to that, external dependencies, such as CSS and JavaScript files, will be cached by the visitor’s web browser after the first visit - this means that instead of loading a lot of superfluous HTML code for every page in your web site the visitor visits, it will quickly retrieve all style and interaction locally from the web browser cache.
Poor accessibility
When it comes to inline JavaScript code, such as in the above example, it’s applied to an element which doesn’t have any built-in fallback interaction handler (i.e., like a link takes you to the URL specified in its href attribute etc). This means that it won’t work when JavaScript, for one reason or the other, isn’t available.
Difficult code maintenance
When it comes to making changes to the code, I’m sure every web developer would agree on that having code in just one centralized location is a lot more preferable than changing exactly the same kind of code snippets spread all over the files in the web site. Maintaining similar code to the above for an entire web site would be hell.

Doesn’t everyone have JavaScript nowadays?

First: no they don’t. Second: some people purposely turn it off (for instance, the NoScript Firefox extension has had 31 million downloads to this date). Third, very often is not up to the end user, but external circumstances that they don’t control, which will, to some extent or another, lead to JavaScript being unavailable. These factors are:

  • Antivirus programs and firewalls being a bit too harsh in their JavaScript security judgement.
  • Company proxy servers filtering out code (for example, read An important lesson learned about AJAX and accessibility).
  • Other company internet access settings preventing proper JavaScript execution.

How you should develop

Any Interface Developer who’s fairly skilled knows that he/she should strive for a structure there the content (HTML code) is completely separated from the presentation code (CSS) and interaction code (JavaScript). What this means is that, naturally, you can’t cut the ties completely, but there should be no inline CSS or JavaScript code in your HTML.

The only acceptable dependencies are through id and class attributes for CSS and JavaScript hook-ins.

Taking the above bad example code, let’s rewrite it properly:


<link rel="stylesheet" href="CSS/base.css" type="text/css" media="screen">
<script type="text/javascript" src="js/base.js"></script>

<div id="container">
    <div id="navigation">
        <a id="get-news" href="news-proper-URL">News</a>
    </div>
</div>

/*
    CSS code, in separate file (base.css)
*/
#container {
    width: 800px;
    margin: 1em auto:
    font: bold 1em/1.2 Verdana, Arial, Helvetica, sans-serif;
}

#navigation {
    float: left;
    width: 400px;
    padding: 1em 2em;
    font-size: 0.9em;
}

/*
    JavaScript code, in separate file (base.js)
*/
window.onload = function () {
    document.getElementById("get-news").onclick = function () {
        // Get news through AJAX
    };
}

A bit nicer, isn’t it?

When to use id and when to use class

Basically, it’s very simple. An id is unique for a web page, i.e. it should only appear once. The class attribute, on the other hand, can be in a document as many times as desired. My rule of thumb is that normally I use the id attribute for larger blocks in a web page, like site container, navigation, main content etc. Otherwise, I always use the class attribute.

When it comes to CSS code, connecting something to anything with that class in the HTML code is very simple. In regards to JavaScript and DOM access, however, native support for that doesn’t exist in all web browsers, Therefore I recommend the getElementsByClassName function, which also supports some other nifty features not available in any native web browser implementation.

Event handling in JavaScript

The code in the example is the old DOM Level 1 way of applying events to an element. It works fine for one event per element, but not if you have multiple events you want to apply, or the risk that someone else’s code will overwrite your event (or vice versa).

To avoid having to bother about event handling quirks between web browser implementations (and believe me, there are some), I recommend using a JavaScript library like DOMAssistant or jQuery instead.

But what about major players, like Google?

So, by now you have hopefully agreed with all my arguments and is ready to take a plunge into the brave new interface developing world. But, just out of curiosity, you take a look at the most popular web site in the world, Google, and think:

Wait just a minute now! Robert is having me on.

The start page, and especially the search results page, is filled with inline styling and JavaScript events. If they do it like that, it has to be the best way, right? Well, no. Google has some crazily talented JavaScript coders, as well as geniuses in other fields, but when it comes to HTML and CSS, they are actually somewhat infamous amongst talented Interface Developers.

In August a couple of years ago, my friend Roger rewrote the Google code with real proper code, and he goes more into detail explaining what he did in his post.

At the end, though, we need to consider the ridiculously high amount of visitors Google get every day, and for them it’s all about performance, performance, performance (for anyone interested in delving deeper into that, please read Improve your web site performance - tips & tricks to get a good YSlow rating). For them, cutting down any HTTP request is crucial, although that’s no excuse for not having valid code.

The most sensible option for Google would be to have one style block located at the top of their HTML code, and one JavaScript block located at the bottom of their HTML code (read more about why in Where to include JavaScript files in a document) and just have id and class attributes to connect that code to.

In the end, though, I really think that the benefit of having the code whatsoever anywhere in the HTML code is negligible, and besides, as soon as we’re talking about returning visitors (for instance, I visit Google each and every day), having external includes would be more beneficial and vastly better for performance as well as bandwidth usage. Also, in comparison, the Google Mobile page is in a much better state, so having the regular one being so poor does really have any valid motivation - I think it’s more of a left behind that hasn’t been seen to properly yet (they’re probably terrified of changing it).

Conclusion

Therefore, as stated above, make sure to include all your CSS and JavaScript code from external files. Start today! Move all inline code away from the HTML code, and you as well as your team and web site visitors will feel better right away. :-)

17 comments

  • Morgan Roderick
    November 20th, 2008 at 22:06

    A very nice writeup Robert.

    I will certainly be referencing this page, the next time I try to explain to colleagues the pitfalls of inline styles and inline javascript :-)

  • Ross Bruniges
    November 20th, 2008 at 23:13

    I think another reason (though this is only a guess) for Google’s old scholl HTML/CSS could be for the fact that they need to support some real old browsers.

    Another reason when using inline JS might be the best idea - heavy commercial sites with listen line/inline player POP-up buttoms at the head of the page (IE before the JS library is included). To stop quick clickers the best way around having the player open in the same window is to put the JS inline and unfortunately this was a critical bug to fix. (any other idea’s how this might be done??).

    Nice article though and good to see performance issues discussed.

  • Mazza
    November 21st, 2008 at 2:38

    I second Morgan’s comment. :) Once again, another great article I will share with my co-workers.

  • Tim Shortt
    November 21st, 2008 at 3:26

    I agree wholeheartedly, and would also add another significant drawback to inline CSS. Using inline CSS eliminates the benefits of CSS specificity. When I see a lot of inline CSS (particularly during maintenance), it’s a good indication that the developer doesn’t understand specificity. Minimize the depth of your selectors during development, and use increased specificity when you need to override a style either for an exception case during initial development or later on during maintenance (rather than taking a jackhammer to the code with inline CSS).

  • Mike Budahn
    November 21st, 2008 at 18:55

    Would you want to create a separate JS file for code that would only ever be used on a single page?

    I suppose as long as its either in another file, or at the bottom of the page you still achieve separation of layout and interaction.

  • Robert Nyman - author
    November 21st, 2008 at 19:43

    Morgan,

    Thank you!

    Ross,

    Regarding old web browsers and Google: I think that web browsers supporting basic CSS formatting are so widespread right now (and have been for quite some time), and with a proper semantic HTML fallback, it would usable for virtually everyone.

    In the case quick clickers, I think that the best way is to include a small JavaScript block at the top being triggered as soon as the DOM (not window) has loaded to apply the proper event.

    That works most of the time, but if not, perhaps just wait till the DOM has loaded and then show such links with JavaScript when the necessary JavaScript functionality is present.

    Mazza,

    Thanks!

    Tim,

    Great point! Inline CSS severely decreases the potential of CSS specificity, and leads to !important scatter def ed all around since the developer doesn’t understand the basics of applying CSS rule.

    Mike,

    If that user reloads the page just once, or revisits your web page before the cache has expired, you will get the same benefits as for code spread across your web site - i.e. lightning fast code retrieval from the cache instead of a superfluous HTTP request.

    Also, with that you will gain separation and better code maintenance as well, and perhaps in the future, that functionality will be available in more pages.

  • Mikael Bergkvist
    November 21st, 2008 at 20:00

    And thus this, and thus that, the eleventh command shall be that we, the cyber priests, shall forever controlleth all and command others, in what is right and what is not, or they shall surely burn in everlasting hell.

  • Robert Nyman - author
    November 21st, 2008 at 23:22

    Mikael,

    Eh… Not sure what you’re getting at. If it isn’t clear, this is about best practices, which will result in a better environment for you as a coder, for your employer getting a better value for their money, and last, but definitely not least:

    A better user experience for the end users.

  • Tino Zijdel
    November 22nd, 2008 at 1:21

    > HTML code will never be cached

    This simply is untrue, although most dynamic sites will force no-cacheing headers for their HTML

    using window.onload is not the best advice either to hook behaviour since this fires only when *all* resources for the page have been loaded (including images etcetera) which often is a substantial delay - especially when a visitor has an ‘empty cache’. You’d better eleborate on DOMContentLoaded, but I myself don’t shy away from using inline javascript in the form of <script> -tags in the body to hook my behaviour as soon as possible (and hope that IE won’t throw “operation aborted” on me)…

    I agree on inline styles though, but a small <style> -directive in the head saving an additional request is sometimes worthwhile.

  • Steven Clark
    November 22nd, 2008 at 7:27

    Another benefit is that you can pass over the valid HTML to team members and not have to worry about someone going in and changing parts to fit their inline CSS and JS…

    So if they’re working on external files you don’t have the CSS guy falling over the HTML guy and the same with the JS guy - if they’re separate.

    BTW nice post Robert.

  • Sunday Weekly Roundup #33 - 11/23/2008 » Blog at veanndesign.com
    November 24th, 2008 at 0:59

    [...] Why inline CSS and JavaScript code is such a bad thing [...]

  • Bruno Bichet
    November 24th, 2008 at 12:39

    Hi Robert,

    I’am a french webdevelopper and sometimes I translate the greatest posts I find on the web. I don’t know if your are skilled in french language, but you can find the translation here : http://www.css4design.com/blog/le-code-CSS-et-javascript-inline-saimal

  • Rani
    November 24th, 2008 at 13:59

    Hi
    Can you direct me to the place in W3C WAI where inline CSS is forbidden?

  • Robert Nyman - author
    November 24th, 2008 at 21:01

    Tino,

    Regarding HTML, let’s say it was simplifying. Since most pages are very alive, so to speak, it’s almost exclusively a deliberate choice not to cache the HTML (or if, then only for a short period of time).

    With window.onload, it’s a starting point, especially in thinking. Then DOMContentLoaded is naturally the best way to go, but then I would have spent quite some writing on explaining which web browsers don’t support, what’s the workaround options etc. Basically, I just felt I would get a little too much off track, although such a solution is definitely the best one in the long run.

    And yeah, there are a few cases where it’s vital that some events are applied as soon as the content is visible, and then a script block can be motivated.

    With inline style, very few are so small that it’s even worth putting in the page itself. Rather, if you have several CSS files, concatenate them to one on the server, and serve a compressed and gzipped version of those, to make the request as efficient as possible.

    Steven,

    Absolutely, separation is key. And thanks. :-)

    Bruno,

    Great, thanks!

    Rani,

    It is not forbidden, it’s about best practices. Just as W3C: it’s not about legislation, only recommendations.

  • SneakyWho_am_i
    December 9th, 2008 at 4:42

    I heard that valid google pages actually make the filesize smaller, even with a full DTD.
    We must remember that when the boys sitting in their little garage with donated and stolen computer parts wrote the main page for google, they weren’t web designers. They’d never written any HTML in their lives, and so it is amazingly good markup for someone’s first ever web page!

    Please note that I’m not citing any sources.

  • Ceriak
    December 13th, 2008 at 19:15

    Great post, Rob, we really do need these! I can hardly believe that in 2008 people just still can’t write well-designed, semantic markup (what am I talking about? They even unable to write a single _valid_ webpage – or just well-formed XML?). Keep up spreading the word!

  • Robert Nyman - author
    December 13th, 2008 at 20:19

    SneakyWho_am_i,

    He he. :-)
    Yes, I personally think they could gain a lot from making pages more valid.

    Ceriak,

    Thank you!

Share your thoughts:

HTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> . If you want to display code examples, please remember to write &lt; for < and &gt; for >.

Comment preview

Top results