Shaun Luttin Shaun Luttin - 2 months ago 17
C# Question

Should I inline all CSS files programmatically to optimize page load speed?

Google PageSpeed often suggests to optimize CSS delivery. It occurred to me that it would reduce network round trips to inline all the CSS like this:

<style type="text/css">

var bootstrap = File.ReadAllText(Server.MapPath("bootstrap.min.css"));
var bootstrapTheme = File.ReadAllText(Server.MapPath("theme.min.css"));
var fontAwesome = File.ReadAllText(Server.MapPath("font-awesome.min.css"));
var bigfont = File.ReadAllText(Server.MapPath("bigfont.min.css"));
var bigfontPrint = File.ReadAllText(Server.MapPath("bigfont-print.min.css"));



This seems to be a reasonable solution to the problem of slow page loads and has increased my PageSpeed score to 95 from 88.

Putting code-style aside for the moment, what technical reasons, if any, exist for NOT in-lining all CSS in this way?


Inlining all your CSS means it cannot be cached, so every single page load will contain all of the CSS required, and when you are using large libraries that can really be a lot of wasted bandwidth. For example, Bootstrap is around 120k. Note the Google link you shared specifies the following (emphasis mine):

If the external CSS resources are small, you can insert those directly into the HTML document, which is called inlining.

So a single page load may be faster but overall it's likely to be slower.

Personally I would stay away from doing that. However, one thing you can do is bundle all of your CSS into a single request (you are using MVC so that is relatively simple) so you only have to do a single extra trip to the server for your CSS and all future pages requested by the browser will not need to ask for them again.