Twitter: reading for class

How To: Optimize Your CSS Even More

Mar 18, 2007 in ,

Over the summer I wrote a post called 5 Ways to Speed Up Your Site that went through some basic tips for getting your site to load faster. I mentioned enabling gzip compression in WordPress and using services that remove the whitespace from your CSS, effectively “compressing” it. Now, I’ll go a bit more in-depth with a simple, yet powerful, PHP method of compressing your CSS.

What We’re Doing

The WordPress method of compression gzip’s your site’s markup, but it doesn’t go so far as compressing your linked stylesheets. To get the benefit of a compressed CSS file (or more, if you have several), I’m going to go a bit deeper by adding this compression directly on each CSS file.

Things You Should Know

All forms of compression, including this PHP method, will utilize a tad of your server’s CPU to compress data. For most this is negligible, but if you know that you are on a flaky, shared-server-using webhost you might rethink using compression on your site. But I mean, it would have to be a flaky webhost.. a $5/year host as from what I’ve seen most decent servers can handle compression no problem.

Also, not every browser supports gzip compression. However, you’d have to be running a very old browser for that case to appear. Kyle Neath tells me that IE 4+, Netscape 4+, Opera 5+ and all versions of Safari and Firefox support gzip compression, so I would say that it is very safe to go ahead with using gzip compression in terms of compatibility.

Edit: The method of gzip compression I will be pursuing utilizes ob_gzhandler which is smart about compressing data..

Before ob_gzhandler() actually sends compressed data, it determines what type of content encoding the browser will accept (”gzip”, “deflate” or none at all) and will return its output accordingly. All browsers are supported since it’s up to the browser to send the correct header saying that it accepts compressed web pages.

Gains

With compression you save bandwidth by having smaller file sizes. For example, my already whitespace-free CSS file was around 9kB before compression. After, it weighed in at only 2.4kB. While that is a great compression rate, let me show you the difference on your typical CSS file. Using digg’s global CSS file as an example - before compression the CSS was 26.3kB and after compression it was only 6kB. Amazing stuff.

Okay Already, Show Me How!

First off, make a copy of your current CSS file and add the suffix “.php” to the file name. If your CSS file was named style.css your new file would be named style.css.php (don’t include this period to the right > ).

Next, update your CSS link to reflect this change. Note: Don’t copy and paste the any of the code below - my blog displays quotes as smart quotes instead of regular ones and this will mess it up. Just type it as you see it.

Before

<link rel="stylesheet" type="text/css" media="screen" href="/style.css"/>

After

<link rel="stylesheet" type="text/css" media="screen" href="/style.css.php"/>

Now to the real part. Open up your style.css.php, or whatever you named it, file and add the following snippet of PHP to the very top:

<?php if(extension_loaded('zlib')){ob_start('ob_gzhandler');} header("Content-type: text/css"); ?>

Then, add the next line to the very bottom and save the file.

<?php if(extension_loaded('zlib')){ob_end_flush();}?>

That’s it! Refresh your site and check it out.

How It Works

The first part of the PHP code checks to see if your server’s PHP installation supports zlib, which is required for the gzip compression we are trying to attain. If that’s all fine and dandy, output buffering begins processing with ob_gzhandler, which creates gz-encoded data if supported by the user’s browser. The last line stops the output buffering and sends the contents of the buffer to the user. It is debated whether or not ob_end_flush() is actually required since it is apparently called automatically by PHP at the end of the script execution, however I kept it in there for good measure.

If you did just the output buffering, this method wouldn’t work since the browser doesn’t know how to parse it. That’s why the header of content-type text/css must be sent out.

What Do You Think?

As of now, this blog’s homepage comes in at 27.6kB from its already lightweight 34kB. If I didn’t have those three sponsor graphics in my sidebar, it would only be about 15kB.

After you have dealt with compression and saving images for the web, the next thing would be optimizing database queries.. but that’s another article or series of articles in itself.

What do you do to ensure that your site runs and loads as fast as it can?

Promote this article on various sites or email to your friends:     



91 Comments

  1. The codes won’t show up in feeds. Now wonder I can’t understand what it’s all about. :) Thanks for the tips!

  2. Yeah, I get a completely blank page in NewsFire.
    Weird.

    Good tip though, thanks.

  3. Yeah I have no idea why it’s doing that..

  4. Very cool script. I’m adding this to all my pages now.

  5. By the way. If anyone copy and pasted Paul’s code and now is getting a blank display, be sure to go back and change the ” (quotes) in your php file. Just delete them and retype them in your text editor. Seems like WordPress is throwing up smart quotes or something and that interferes with PHP code.

  6. Yeah that’s an issue with my code plugin. =/

  7. I do the same thing with my CSS files. You should also probably send out the charset like this: header(”Content-type:text/css;charset=utf-8″). I also enable caching by outputing a last-modified header and returning a 304 if the representation hasn’t changed. In addition, you can send an Expires or Content-control: max-age header to specify how long the file can be cached.

    Anonymous Coward on Mar 18th, 2007 at 1:30 pm
  8. If anyone finds a plugin that does not spit out smart quotes for code, do share. I think this is something that a lot of WordPress users are looking for. I used to use the same plugin Paul, but after seeing that it basically rendered the code snippets useless, I disabled and went back to using <code> around web safe converted code - Postable.

  9. For those with the Smart Quote problem, I’ve always used this plugin and never had a problem.

  10. Why not mess with the css but do the same with the addition of 2 separate files. I find this cleaner

    1. Drop a .htaccess in your css folder or just add this to your main .htaccess

    AddHandler application/x-httpd-php .css
    php_value auto_prepend_file gzip-css.php

    2. of now, you will need the gzip-css.php with the following code

  11. Paul,

    The plugin you linked is nice, but it has an insane amount of file inclusions.

    I just tried out “SyntHihol”, http://www.indyjt.com/software/synthihol/SyntHihol.zip

    It highlights whatever language you define, using GeShi. Doesn’t include any external JS or CSS files as far as I can tell. Best of all, it’s easy to toggle the styling.

    For a quick demo, see: http://patrickmn.com/2007/03/19/appetizer-easiest-proxy-server-ever-with-python-and-twisted/

  12. This is a good tactic, but it’s adding load to your web server by having to do this every request. It would be more efficient to use caching or compress it once and make it a static css file.

    http://www.codeandcoffee.com/2007/01/19/how-to-compress-your-css/

    Sure the load isn’t much until your page hits spike, like on popular blogs. In situations where you blog and data is dynamic, it’s best to make PHP and your database work as least as possible… dynamic is only good to a certain extent and for data that is changes a lot.

  13. @matthew - the site you liked to talks about css compressor which only removes whitespace, comments and things like that. That’s much different than this gzip compressing, although I do use both methods. But in general, you’re right - cache where and when you can.

  14. Current, I know it only removes whitespace… but you could cache your gzip results so the server and PHP does not need to do this every page hit.

  15. Writing code in WordPress is a pain, but fixing your code is actually very easy, and essential to avoid all the whines and complaints. There are some simple instructions in WordPress.com Blog Bling: Signatures and Writing Code in the second half of the article that will help, along with some online tools for fast converting if you don’t want to do a little search and replace in a text editor.

    I post code on my blog constantly, and so I’m very familiar with this issue.

    Very great tips. I hope my tip helps you make them better. ;-)

  16. umm why not just gzip the css? the http 1.1 spec allows for gziped data… set the mime type to x-html it should still render as css though.

  17. nathan - there are multiple ways of gzipping your CSS. the way you mentioned works just as well.

  18. Paul, is there some option to have it sitewide for all CSS files and not just the style.css file??

  19. Awesome, I used this and the css-compress plugin on my blog. Now I have my shoutbox plugin sending itself compressed. Before it was one of the biggest code that the browser had to download

  20. Neat Trick Paul!

    For something more sophisticated, which may be useful in other situations:

    The Definitive Post on Gzipping your CSS

  21. Right, one more thing, you may want to send a full set of headers with what you are doing, or else you risk having the browser *not* cache the CSS file and request it every time. I did a bunch of testing when I looked at this back in 2004 and most of the browsers only cached the CSS file if it came with the proper expires headers.

    See the file I linked above for the details.

  22. Mike thanks for pointing this out… Am looking at the tutorial now. Would this also be the case for other type of files, like js files?

  23. Hey Ajay,

    For sure. Basically, what’s happening here is the file is being “served” by PHP, rather then Apache (or whatever), so the headers are no longer being handled by the server, but by the scripting language.

    If you have a local setup that you can test on, try this out locally and check the log files (I played with this stuff here, ). You will see if your caching is working etc.

  24. I have a local setup, so will take a look.

    But, I really like the gzip solution.

  25. This is not great.
    IT´S PERFECT!!!

    I reduced my site from good 43KB and bad 42HTTP requests to
    unbelievable 29KB and only 18 HTTP requests.
    This is stunning!
    I am searching non stop for methods to reduce site loading time.
    At first the site had about 92KB and with every new method I reduced it
    a bit.
    Thank you Paul!

  26. Great post. Thank you for the info. I’ll make a reference about it on my blog.

  27. using it. loving it. thanks!

  28. Great! Thanks for this how to! …markus

  29. Hello, it might be simpler just to do:

    instead of checking for the library. ‘@’ should suppress the warning message!

  30. Do you really think that doing an unique js file, compressing it with JSmin (or similiar) and doing a gzip of that file really worth?

    Because all that parsing functions, joining, parsing and compressing here and there would result in a greater load time for this files, I mean, would you do a simple gzip?

  31. Great resource m8, I’m going to work at implementing this on my webpage.

  32. Nice article. I’ve seen it in a couple of places before but never seen the code behind it.

    Cheers for the post

  33. I thought I would add that the CSS Compress WordPress Plugin not only compresses the CSS file, but also compresses the images referenced within the CSS file and sends everything to the client in a single gzip file.

    This eliminates the need to combine images into a single file and use image maps, because the number of HTTP requests would be the same either way. I verified this plugin by testing my page under several scenarios using WebSiteOptimization.com. Unfortunately, the plugin works only on the main template CSS file, not any CSS files used by plugins. If you’re using WordPress, the CSS-compress plugin is an easy way improve performance.

  34. Thanks, I’ve been looking for how to gzip my CSS. This rocks.

  35. This looks very interesting. Have used the Icey CSS compressor, but never have gone into depth on this subject since I am not a programmer. You make it sound so easy with simple instructions. Much appreciated.

  36. Thanks, I’ll definitely tag this page for future reference, will definitely come in handy.

    If you are having trouble displaying code in Wordpress I have written a post (http://carltondickson.co.uk/2008/03/02/displaying-source-code-in-wordpress-post/) that could help, I would definitely recommend the Google Syntax Highlighter (http://wordpress.org/extend/plugins/google-syntax-highlighter/) admitedly it does include all highlighters C++/XML/JAVA but these can easily be removed using the plugin editor and removing the script tags containing the brushes you don’t need.

    @Vladimir Nikolic It’s always nice to discover ways to reduce the page load and performance of your pages….I would urge you to install YSlow, it’s a firefox plugin for another firefox plugin - firebug. They reguarly talk about ways to serve pages faster, I checked your site and there are definitely plenty of things that you could do to reduce the page size even more, give me a mail if you need any help :)

  1. [...] How To: Optimize Your CSS Even More - PaulStamatiou.com (tags: css webdev wordpress HowTo optimization reference paulstamatiou) [...]

  2. [...] Paul has the low-down on how-to with PHP for those of you without server [...]

  3. [...] Wordpress as the blogging software of choice for Ghacks and all of my other blogs. After reading Paul Stamatious article on optimizing CSS for Wordpress I decided to give it a try and see if page loading times [...]

  4. [...] Wordpress loading times After reading Paul Stamatious article on optimizing CSS for Wordpress I decided to give it a try and see if page loading times [...]

  5. [...] Stamatiou explains how you can easily compress your CSS files to make your web page load much [...]

  6. [...] 优化你的 CSS & 用 PHP 压缩你的 CSS [...]

  7. [...] How To: Optimize Your CSS Even More - PaulStamatiou.com [...]

  8. [...] optimization wasn’t enough, I also recommend Paul Stamatiou’s PHP [...]

  9. [...] Cardboard Furniture (Tags: tutorial design furniture)22 - Toughest Games to Beat (Tags: games)23 - Optimize Your CSS Even More (Tags: webdesign css)24 - Andy Rementer (Tags: portfolio design [...]

  10. [...] için, CSS dosyanızı Gzip kullanarak sıkıştırıp, öylece tarayıcıya yollayabiliriz. How To: Optimize Your CSS Even More başlığı hoşuma gitti ve aynı konuyu ben de ve kendi dilimde işlemeye karar verdim Şimdi [...]

  11. [...] 这个工具是在一篇优化CSS文章中发现的,他说在WordPress中把CSS后缀名改为.php,然后利用gzip压缩的方式来优化CSS,这个方法我只在国外一些插件附带的css上看见过。 [...]

  12. [...] 早就想对blog优化一下,尤其是在不断的添加插件之后,各项加载都在增加,包括css也在不断增长,十分头痛。从Nicky那看到在线网页分析工具,它可以帮助你查看页面中的HTML、JS、CSS代码和图片各自的大小,再计算出不同的带宽下的加载速度,最后给出一个建议,提示你哪部分该优化了。于是就去试了一下,我的“Congratulations”有点偏少了。 于是通过Nicky提到的一篇优化CSS的文章进行了优化,可是不知什么原因,开始调试没问题,可后来就怎么也没法调用style.css.php,只好换了几个compress css,并且自己也通过提示改了一些设置和代码。 这是 codeandcoffeeçš„ JavaScript Compression tool, 的结果:Old Size: 6774 bytes  New Size: 5371 bytes  Ratio: 79.3% 最后用的是the exact little script 压缩到了48**bytes。 [...]

  13. [...] 第一种我们是没法办到,第二种方法不错,可以一劳永逸,一、二种方法效果都一样,就是对所有php后缀文件进行压缩。我这里主要介绍一下第三种方法和WP自带的功能配合使用,参考“How To: Optimize Your CSS Even More”。 [...]

  14. Optimiza los archivos CSS…

    Interesante artículo que muestra como, utilizando la compresión gzip (un método de PHP), se puede comprimir (optimizar) el archivo CSS de un sitio para lograr una descarga más rápida.
    Leer artículo en: http://p...

  15. [...] 这个工具是在 一篇优化CSS文章中发现的,他说在WordPress中把CSS后缀名改为.php,然后利用gzip压缩的方式来优化CSS,这个方法我只在国外一些插件附带的css上看见过。 [...]

  16. [...] How To: Optimize Your CSS Even More - PaulStamatiou.com (tags: css optimization compression howto) [...]

  17. [...] een goede beginnerscursus CSS positionering in 10 stappen, tot het optimaliseren van je CSS code voor de meer ervaren [...]

  18. [...] CSS Datei mit gzip Komprimieren: Entweder mit dem Plugin css-compress oder von Hand mit ein paar Zeilen Code. [...]

  19. 5 Ways to Speed Up Your Site…

    Throughout the blogosphere I’m always seeing these blogs, that while they look great, are horribly slow and overburdened. Over the past few months I have become somewhat of a website optimization specialist, bringing my own site from an over 250…

  20. [...] / Ideas: 1. paulstamatiou.com 2. randomnetworks.com Let others know about this site, use icons below These icons link to [...]

  21. [...] Compressed and optimized the CSS per Paul Stamatiou’s great article. [...]

  22. CSS creme of the month…

    Every once in a while we try to identify what's hot in one of our categories and this time we picked CSS since it's becoming more popular with each day that goes by. More and more web designers become interested in learning every trick. A good …

  23. [...] google到一个好方法(英文),将css或者js文件模拟成php文件用gzip压缩后输出.方法如下: [...]

  24. [...] pour présenter une technique d’optimisation des CSS en PHP, présentée il y a peu par Paul Stamatiou sur son blog. Celle-ci permet de réduire une feuille de style de 35kb à environ [...]

  25. Have you optimised your site code?…

    Website optimization is an important process for every webmaster trying to reach “the top”. It includes several parts, some of which may not be plausible for all. Optimisation refers to the cleaning of code markup, images and backend so tha…

  26. [...] google到一个好方法(英文),将css或者js文件模拟成php文件用gzip压缩后输出.方法如下: [...]

  27. [...] google到一个好方法(英文),将css或者js文件模拟成php文件用gzip压缩后输出.方法如下: [...]

  28. [...] leyendo un poco más sobre como hacer archivos CSS más pequeños, llegué a un muy interesante artículo de Paul Stamatiou donde muestra una manera de reducirlos mucho más, lo cual al principio vi con ojos un poco [...]

  29. [...] | Paulstamatiou Y ahora qué hago? Suscríbete a Pablogeo Suscríbete por correo [...]

  30. [...] Comment optimiser vos CSS un peu plus ? Grâce à PHP… [...]

  31. [...] un interesante artículo de Paul Stamatiou donde se muestra una manera de reducirlos mucho más los archivos CSS realmente [...]

  32. [...] How To: Optimize Your CSS Even More baÅŸlığı hoÅŸuma gitti ve aynı konuyu ben de ve kendi dilimde iÅŸlemeye karar verdim Åžimdi PHP’nin ob_gzhandler fonksiyonunu kullanarak Gzip yönetimi ile CSS dosyamızı sıkıştırarak tarayıcıya yollayacağız. [...]

  33. [...] Alternatively, you can check out my method of CSS compression utilizing PHP. [...]

  34. 12 Articles and Tools for CSS structuring and optimising…

    Optimising and structuring your CSS file is important, especially when you have a large stylesheet. Optimising and structuring your site makes your stylesheet more readable, which makes it easier to update. It can also make your CSS file smaller in si…

  35. [...] How To: Optimize Your CSS Even More [...]

  36. [...] 这个工具是在一篇优化CSS文章中发现的,他说在WordPress中把CSS后缀名改为.php,然后利用gzip压缩的方式来优化CSS,这个方法我只在国外一些插件附带的css上看见过。 [...]

  37. [...] How To: Optimize Your CSS Even More başlığı hoşuma gitti ve aynı konuyu ben de ve kendi dilimde işlemeye karar verdim Şimdi PHP’nin ob_gzhandler fonksiyonunu kullanarak Gzip yönetimi ile CSS dosyamızı sıkıştırarak tarayıcıya yollayacağız. [...]

  38. [...] How To: Optimize Your CSS Even More [...]

  39. [...] format your CSS files to your liking. There are also options serve zip versions of your CSS files using PHP. You can find more CSS compressors and optimizers in the post List of CSS [...]

  40. [...] format your CSS files to your liking. There are also options serve zip versions of your CSS files using PHP. You can find more CSS compressors and optimizers in the post List of CSS [...]

  41. [...] format your CSS files to your liking. There are also options serve zip versions of your CSS files using PHP. You can find more CSS compressors and optimizers in the post List of CSS [...]

  42. [...] format your CSS files to your liking. There are also options serve zip versions of your CSS files using PHP. You can find more CSS compressors and optimizers in the post List of CSS [...]

  43. [...] format your CSS files to your liking. There are also options serve zip versions of your CSS files using PHP. You can find more CSS compressors and optimizers in the post List of CSS [...]

  44. [...] format your CSS files to your liking. There are also options serve zip versions of your CSS files using PHP. You can find more CSS compressors and optimizers in the post List of CSS [...]

  45. [...] 另外,利用Gzip功能压缩CSS,可以有效的减少网页大小.我原本的CSS文件经过TopStyle清洁后大小为12K,压缩后变成3K,效率很强大。Wordpress用户可以安装CSS Compress插件,也可以自己手动修改文件,机制都是一样的。不过这个是需要服务器支持zlib,建议Linux主机的用户采用。其他的那些在线CSS压缩网站,工具如CSS Tidy,CSS Compressor等等是治标不治本,用处不大,一些常见的CSS编辑器(比如TopStyle,Rapid CSS)都有整理CSS冗余代码的功能。 [...]

  46. [...] format your CSS files to your liking. There are also options serve zip versions of your CSS files using PHP. You can find more CSS compressors and optimizers in the post List of CSS [...]

Post a comment, receive Stammy points.


Send a trackback.


  • If you plan on posting code, run it through Postable first.
Copyright © 2005 - 2008 PaulStamatiou.com  Privacy Policy - Terms of Service Can't spell my name? Use PSTAM.com. Go back up ↑.