One way to improve your page load speed is to inline CSS and JavaScript and all this means is that you include both in your HTML file.
You should have the inline small CSS inside the ‘’ tag while the inline JS can be in the ‘’ or ‘’ tag. Most of the time, best practice dictates that you should call JS and CSS using an external file, but you can include snippets of both in the HTML, saving multiple round trips, and speeding things up a little.
Many of the top site speed test tools recommend inlining CSS and JS and it is relatively easy to do. However, you do need to be careful that you don’t overdo it and inline too much.
Example of Inline Small CSS and JS
To give you an idea how to do it, this example shows you what your HTML file may look like when CSS and JS are inlined. We’ve enclosed the CSS inside ‘
‘<html>
<head>
<title>Inline Small CSS & JS Example</title>
## Start Inline CSS
<style>
body{background: #f5f5f5;}
a{color: #24890d; text-decoration: none;}
h1{font-size: 26px;line-height: 1.3846153846;}
</style>
## End Inline CSS
</head>
<body>
……
## Start Inline JavaScript
<script>
JavaScript code…
</script>
## End Inline JavaScript
</body>
</html>’
If you have got several small CSS or JS files, the code from each one may be inlined in the HTML file but do keep an eye on the overall size of the file.
Drawbacks
As with everything, there are a couple of drawbacks to inlining CSS and JS, more specifically, a tradeoff between caching and requests.
When you include the resources in the HTML file, you don’t need to make the extra requests to the resource but, where your resource file is quite large and mostly static (it doesn’t change much), it is probably best not to inline it, so the browser can cache it.
The biggest drawback of inlining is that CSS and JS can’t be cached because the browser can’t store what is in the HTML file.
This means that the entire HTML file needs to be fetched every time and, if it is full of CSS and JS, then it could be far more detrimental than retrieving the CSS or JS individually.
For this reason, you must be careful about how much you inline and don’t bloat the HTML file out.
Benefits
The benefits of inlining CSS and JS include fewer round trips thus reducing loading time so, if you some files that have only a little CSS or JS in them, it is worth adding to them to the HTML to make page loading more efficient.
This is also the recommended method to use if you want to cut down the latency caused by CSS, resulting in the critical path being optimized.
As said earlier, don’t overdo this. If the CSS and JS files are too large it is better to let them be cached rather than having to call a bloated HTML file every time.
Alternatively, if you can’t inline then another way is to combine small CSS into one external file and JS into another and call them that way – this also cuts down on round trips and boost page speed.