YiiHaa Webdevelopment blog about Yii-framework and more


Minify and merge your CSS and JavaScript

It is good practice to optimize CSS and JavaScript for lower load time, it is never good to have a lot of <link ref="stylesheet" href="...> or <script src="...> tags in <head>. Here are some rules of thumb you might find useful. For starters you should only add CSS and JavaScript to <head> when you need it. For example: Do not load that bit of JavaScript that validates your contact-form if you are not displaying the contact-form on that page. In Yii you can seperate this easily by using:


or for CSS:


After you have made sure you are not loading all your CSS and JavaScript all of the time you should focus on reducing your code to a minimum. Minifying your code decreases the load-time of pages and makes your website look more responsive. You can use CSS/JS-minifiers for this, personally I found JSMin a good one for minifying JavaScript and I wrote my own minifier for CSS. My CSS-minifier is not the smartest minifier as it does not clean everything out of the CSS, but it is lightweight and does the majority of the minifying I can imagine.

After minifying your CSS and JavaScript you could do one more thing: combining your CSS and Javascript into one file (one for CSS and one for JavaScript of course). Combining the files is good practice because it decreases the load-time of a page even more. Due to the browser its limitation on the number of connections per domain your pages will load longer when you have too many external files to load. I have written my own MinifyClientScript that I can hook into Yii to minify and combine all CSS and JavaScript files to make this happen. You could also choose to install Google's Page Speed module into Apache to get a lot of this done.

You can download the files I used to minify CSS/JavaScript from my extension page on yiiframework.com HERE. You can also post comments/ask questions about it there.

Posted by Klaas

Comments (7) Trackbacks (0)
  1. thanks very much for the extensions :)

  2. great extension,
    it helps me so much.

  3. I have to tell you that it’s hard to find your posts in google,
    i found this one on 19 spot, you should build some quality backlinks in order
    to rank your webiste, i know how to help you, just type in google – k2 seo tips and tricks

  4. I see a lot of interesting content on your website. You have to spend a lot of time writing, i
    know how to save you a lot of work, there is a tool that creates unique, SEO friendly articles in couple of minutes, just search in google – laranita’s free content source

  5. I am new to yii, i want to configure the extension in my yii. Can someone please tell me how to do this. In which file i have to do the modification. and what to add.

Leave a comment

No trackbacks yet.