Pre-compressed CSS and Javascript

Do you have large stylesheets (CSS) and Javascript files that are referenced on pages in your site?

By compressing those files you could cut down on your websites bandwidth and user response times.

A great place to start is by turning on mod_gzip or mod_deflate to automatically compress your files before returning them to the user. This is a module that will compress some / all output just before it is returned to the user. This method is probably the best approach for most users, provided that their webhost provides these modules.

It is possible to save additional server processing time (which translates into faster response times) by pre-compressing any static files - i.e. javascript and css files. However you need to ensure that users with unsupported browsers can still access your content.

So, you could keep two copies of the files on your server, the compressed, and the uncompressed and then serve the correct one back to the user based on their browser support.

To do this in your .htaccess file or httpd.conf files, add the following lines:
FilesMatch "\.css.gz$">
ForceType text/javascript
Header set Content-Encoding: gzip

RewriteCond %{HTTP:Accept-Encoding} gzip
RewriteCond %{REQUEST_URI} \.(js|css)$
RewriteRule ^/(.*)$ /$1.gz [L,QSA]

The first "FilesMatch" section just sets the correct encoding type to be returned to the users browser if you are returning the compressed version of the file.
The second section checks to see if a users' browser supports compression (gzip), then return the .gz version of the file instead of the uncompressed one.

Now to make the launch process easier, we could build a script to automatically create the compressed versions of the files whenever a change is made.

I wrote the following in perl, but it can easily be translated to other languages. It just recursively goes through all directories and generates the compressed (gzip) version of all CSS and Javascript files.

!/usr/bin/perl
use strict;
my $DIR = './html_files'; # Base directory where all user accessible live
compress($DIR);

sub compress {
    my ($dir) = @_;
    opendir(DIR, $dir);
    foreach (readdir(DIR)) {
        my $file = $dir."/".$_;
        if (-d $file && $_ !~ /^\.$|^\.\.$/) {
            compress($file);
        } elsif ($file =~ /\.(js|css)$/) {
            `gzip -c $file > $file.gz`;
        }
    }
    closedir(DIR);
}

UsableLayout can help you with optimizing your site performance. Take a look at our development services for an idea of some of the work we do and contact us for help or an estimate of development work you want done.

Comments

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

More information about formatting options