Why Not Embed Styles/Scripts in HTML Instead of Linking?

cssfront-endhtmljavascript

We concatenate CSS and JavaScript files to reduce the number of HTTP requests, which improves performance. The result is HTML like this:

<link rel="stylesheet" href="all-my-css-0fn392nf.min.css">
<!-- later... -->
<script src="all-my-js-0fn392nf.min.js"></script>

If we've got server-side/build logic to do all this for us, why not take it one step further and embed those concatenated styles and scripts in the HTML?

<style>.all{width:100%;}.my{display:none;}.css{color:white;}</style>
<!-- later... -->
<script>var all, my, js;</script>

That's two fewer HTTP requests, yet I've not seen this technique in practice. Why not?

Best Answer

Because saving HTTP requests is of little use when you achieve it by breaking caching. If the stylesheets and scripts are served separately, they can be cached very well and amortized over many, many requests to wildly different pages. If they're mushed in the same HTML page, they have to be re-transmitted with every. Single. Request.

This page's HTML, for example is 13 KB right now. The 180 KB of CSS hit the cache, and so did the 360 KB of JS. Both cache hits took minuscle amounts of time and consumed practically no bandwidth. Whip out your browser's network profiler and try it on some other sites.