Robert has been working with web developing, mostly interface coding, since 1998. His biggest interests lies in HTML, CSS and JavaScript, where especially JavaScript has been a love for quite some time. He regularly blogs at http://www.robertnyman.com about web developing, and is running/partaking in a number of open source projects (http://code.google.com/u/robnyman/). Robert is a DZone MVB and is not an employee of DZone and has posted 60 posts at DZone. You can read more from them at their website. View Full User Profile

Why Inline CSS And JavaScript Code Is Such A Bad Thing

11.28.2008
| 30016 views |
  • submit to reddit

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.
References
Published at DZone with permission of Robert Nyman, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Toomas Römer replied on Fri, 2008/11/28 - 8:08am

There are no advantages explicitly pointed out. I do like the part that the number of HTTP requests go down. Are there any other benefits from inlined CSS and JS?

James MacFarlane replied on Fri, 2008/11/28 - 10:03am

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.

While I agree, the problem here is the implementation, not the inline use of inline JavaScript itself. I believe the premise of this article is flawed. There are proper, accessible, degradable methods for doing this. This example is just one that doesn't do that.

Gavin Blair replied on Sat, 2008/11/29 - 10:25am

 Nice article, I didn't know that inline Javascript was a no-no.

Your final example might be more convincing without unnecessary <div> tags. If your navigation is a list of links, it's nice to use unordered list tags, so those who don't have css can still see a list menu.

 A nicer example of separating content from style could be

<ul id="navigation"> 
<li><a href="news.html">News</a></li>
</ul>
Of course, this does take extra css to style the list item tags, but it's worth it for more readable code and accessibility.
Cheers,
Gavin

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.