Notes

Super Smart Caching

birthed on
May 22, 2008

Rockerboo, Virb’s own brilliant programming, just tipped me off to an amazing way to cache images and javascript client-side from these guys (http://www.mnot.net/cache_docs/#IMP-SERVER). All you need is mod_expires and mod_headers turned on, an .htaccess file in the root of your website and the following piece of code in the .htaccess file:

### activate mod_expires
ExpiresActive On

### Expire 1 month from when they're accessed
ExpiresByType image/gif A2592000
ExpiresByType image/png A2592000
ExpiresByType image/jpeg A2592000
ExpiresByType text/css A2592000
ExpiresByType text/javascript A2592000
ExpiresByType text/js A2592000

I should note that this is smart and knows when you’ve uploaded a new version of a file and will not use the previously cached version.

While you won’t notice a difference the first time you hit the website you will notice a significant difference once you start clicking around. I’ve implemented this here on Teevio.com and on Outforaride.com. Load times on Out For A Ride dropped from about 5-6 seconds on graphically intense pages to about 1 second. Even Teevio.com which doesn’t have a very fast server became very snappy. I’d highly suggest any web-developer to implement this very simple caching method.

Comments

Andrew Cornett
May 23 at 12:13pm

What about mod_gzip? I’ve been running some speed tests and compared my website to digg.com and noticed that somehow they aren’t loading any “css images” … under the results it says this website is compressed using HTTP compression with mod_gzip.

I guess I have to look into it more, but this will definitely help as well! thanks for the post!

Teevio
May 23 at 1:23pm

Yes, that is server/browser side compression and will significantly help page loads as well.

The caching that I mentioned above will prevent the browser from loading an image that it has already tried to load before.

rockerBOO
Jun 05 at 9:53am

Just wanted to add some updates. I seemed to overlook some of the problems that could occur.

This works great on items that the URL is unique, and the content never changes. So thus some problems come up if you update a file, and the file name is not unique. The solution to this is to either set a Last-Modified header for every file, or to make the URL unique. The second one might be a little easier to pull off depending how you have your coding setup. So adding something like this might work.

http://us3.php.net/manual/en/function.filemtime.php#81194

Spammers will be prosecuted under the fullest extent of the law. Or at least marked as spam in my mailbox.

Projects