Coding with Jesse

When to use inline JavaScript and CSS

December 10th, 2006

Unobtrusive Ajax is about keeping all JavaScript and CSS out of the HTML. This is a good idea. You certainly shouldn't be using onclick or onmouseover attributes in your HTML, and you should really avoid using the style attribute. But what about putting JavaScript inside a <script> element or CSS in a <style> element directly in the HTML?

Most people would recommend that you never do this, that you keep every line of your JavaScript and CSS in an external file. I'd say, never say never. There are certainly occasions I do this, although rare, but I think these scenarios make sense. So let me outline some of these scenarios where you may want to use inline JavaScript and CSS:

  • The JavaScript or CSS is specific to one page

    You may be doing something really specific, such as some animations or ajax in a web application interface, where this code won't be reused on any other pages on your site. In this case, you won't gain any benefits of reuse in an external file.

  • The page won't be accessed very often

    If the page is an obscure page in your web application that users only access once, or only once every few months, then you won't gain the benefits of having the browser cache these external files. You'll actually slow things down by making the browser make two extra requests for the JavaScript and CSS.

  • You just want to use a few lines of JavaScript or CSS

    This is a common scenario with a lot of JavaScript libraries. The instructions often involve including an external file, then putting maybe 1-3 line of JavaScript on the page that initializes some widget. It would be totally wasteful to create an external file containing only 1-3 lines of code. The time wasted downloading an extra file would counteract any benefit gained from caching the file later.

These scenarios don't happen so often. As long as you don't care about the browser caching the CSS and JavaScript separately, and you don't need to reuse the CSS and JavaScript throughout your site, or it's just a few lines of code that isn't worth caching, I see nothing inherently wrong with using inline JavaScript and CSS. Your visitors won't notice or care. It's even valid still, as long as you keep the <style> in the <head> and wrap your JavaScript in a CDATA (for XHTML). So if it makes things a bit easier for you, I say go for it.

About the author

Jesse Skinner Hi, I'm Jesse Skinner. I'm a self-employed web developer with over two decades of experience. I love learning new things, finding ways to improve, and sharing what I've learned with others. I love to hear from my readers, so please get in touch!