start blog post

The Three Cs of Fast CSS and JavaScript

One major "best practice" from both Yahoo! YSlow and Google Page Speed is minimizing HTTP requests. Yahoo! indicates that "80% of the end-user response time is spent on the front end. Most of this time is tied up in downloading all the components in the page: images, stylesheets, scripts, Flash, etc." cite

What does this mean? The fewer calls your page makes to the server, the faster your page is. Here are three ways to drastically improve your site response time:

  • Combine your stylesheets and scripts so that you only have to load one CSS file and one JS file.
  • Compress and minify the combined files so you save bandwidth and transfer time.
  • Cache the compressed output so your server doesn't have to repeat the process for each new visitor.

Here's one way to accomplish this:

<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" type="text/css" href="load.php?type=css">
    </head>
    <body>
        ... website content ...
        <script type="text/javascript" src="load.php?type=js"></script>
    </body>
</html>
<?php
    
    /**
     * The following directory structure is assumed:
     * css/
     *     reset.css
     *     style.css
     * js/
     *     jQuery.js
     *     main.js
     * index.php
     * ...        (the rest of your webpages)
     * load.php   (THIS code block)
     */ 
    
    error_reporting(0);       // supress errors (browsers will see them as invalid CSS/JS)
    ob_start('ob_gzhandler'); // compress with GZIP
    
    $isJavaScript = ($_GET['type'] == 'js');
    if ($isJavaScript) {
        $type = 'javascript'; // content type
        $ext = 'js';          // file extension
        $files = array(       // TODO: modify this list based on your own JS files
            'jQuery',
            'main'
        );
    } else {
        $type = $ext = 'css'; // content type is the same as the extension
        $files = array(       // TODO: modify this list based on your own CSS files
            'reset',
            'style'
        );
    }
    
    header("Content-Type: text/$type"); // set the appropriate content type
    $cache = "$ext/cache.$ext";         // for example, css/cache.css
    if (!file_exists($cache)) {         // see if we've already created a cache
        $toCache = '';
        foreach ($files as $f) {
            $f = "$ext/$f.$ext";        // for example, css/style.css
            if (file_exists($f)) {
                $c = file_get_contents($f);
                if ($isJavaScript) {
                    include_once('jsmin.php');     // get JSMin here
                    $toCache .= JSMin::minify($c); // slow, but only called when there is no cache
                } else {
                    // quick and easy way to minify CSS, removes multiple spaces and blank lines
                    $toCache .= preg_replace(array('/\s\s+/', '/\n/'), array(' ', ' '), $c);
                }
            }
        }
        file_put_contents($cache, $toCache);
    }
    readfile($cache);
    exit;
    
?>

The first time the script is called (ever), it may take a few seconds to generate the cache file, but every time after that it will load extremely quickly due to the "three Cs" implemented above. Since minification is part of the process, you can work directly with unminified and commented code on the server, and let the script minify it for you. If you normally load 3+ stylesheets or scripts, you will see a massive performance boost with this type of script.

If and when you change any of your CSS or JavaScript, just delete the cached file and everything is automatically updated on your site's next visit.

Do you have a favorite method of combining scripts to improve website performance? Please share it in a comment!

var tags = [, , , ];

  • share this post:
  • email a friend
  • float this post
  • digg this post
  • share on stumbleupon
  • submit to technorati
  • tweet this post

end blog post

5 Comments

avatarDonnie

An interesting way to speed things up. With CSS and JS heavy sites this method could help. I'm going to give it a go and see if it speeds things up for my users.

avatarHB

Cool. Let me know if you have any trouble integrating it, or if you have ideas to make it even better.

avatarGarmin Portable GPS

Thanks for the info

I Hope can use some of this script in advance. because until now, I'm still using a free theme for my blog.

avatarRichard K. Szabo

This does indeed work very good, will speed up access immensely due to less http-requests, less disk-reads, client-side cache and whitespace-removal.
The code I wrote 6 months ago is rather similar, but I have my own output-handler which compress even more.

avatarHB

Richard, thanks for posting. I used gzip because it's easy and built-in, but I'm sure there are better compression algorithms. Do you have your code posted somewhere? I'd be interested to see it.