Embed CSS in Your HTML for Faster Load TimesWritten by Mark Sanborn: Jun 24, 2008
Most web designers know that reduced server requests equals faster load times. I got to thinking and I was wondering why is CSS always in a seperate file from regular HTML? Usually it is in a different file because you don’t want to make a ton of changes in individual files. Rather you would want to make one change in a .css file and have it change every page of your site; however, with PHP we can embed CSS into our HTML and still have only one file to make our changes.
PHP has a function called include. What it does it include anything in a text file and add it to the current file. This allows us to actually embed the css into our HTML pages reducing the server requests thus faster load times. It also allows us to maintain only one file that will make site wide changes. Thus completely eliminating the need for CSS to be in a seperate file from our HTML.
I have thought about it for awhile and I don’t see any reason to keep css in a seperate file. After looking at Google’s source code I found that they do this exact thing. They don’t point to a seperate css file. Rather they embed the CSS into their HTML.
Update: After doing some research based on some of the comments I received I found this article written by the Steve Souders, who is Yahoo’s Chief Performance guy. The conclusion is that embedding your CSS in HTML is only beneficial if you have a page that is typically loaded only once per session. This explains why Google uses this method. On a blog type site most of the page are the same and will benefit from external CSS rather than embedding into HTML.
He goes on to say:
If you want to make your sites optimized like the kings of optimization (google) then all you have to do is…
Embedding CSS into your HTML
To embed CSS into your HTML with PHP all you have to do is replace your current css call:
<style type="text/css" media="screen"> <!-- @import url( <?php bloginfo('stylesheet_url'); ?> ); --> </style>
<style type="text/css" media="screen"> <?php include('style.css'); ?></style>
This of course will require your server to run PHP. If you use ASP you will have to use the ASP include function and ASP syntax.
Note: If your CSS file points to relative paths for images you may have to fix them for this to work.
Do you compress your CSS and embed it?
Need to print shipping labels on your site?
Checkout my product RocketShipIt for simple easy-to-use developer tools for UPS™ FedEx™ USPS™ and more.