With the release of Yahoo’s YSlow plugin for Firefox, web developers are better able to see how fast their web sites are loading, and improve this load time with some nifty server-side adjustments and on-page changes.

In a series of posts I will be discussing some of these elements, starting this week with caching page elements to reduce server load and make pages load faster.

Cache Pages

One of the problems with page caching is over-caching, where virtually every element on the page is cached meaning the user will see an outdated version of a page until the cache is refreshed or they delete their browser cache.

This cache problem isn’t the case as long as the name of images, elements and files are changed each time a new version is uploaded to the server as the browser will then cache the new version and ignore the old.

YSlow - Chacing PagesThe image shows YSlow integrated with Firebug. The line outlined in red is what we are interested in today for caching purposes.

In this example I had an F rating because of off-server elements, I.e. Google Adsense code.

We have little control over the caching ability of such thing, however we can control elements of our own web sites.

On Apache the caching is carried out server-side, which means we need to create an .htaccess file. The .htaccess file is simply a text file.

This can be written in notepad or equivalent. It is important to save the file as .htaccess, not .htaccess.txt.
To do this in notepad

1. Load a new page
2. Enter the code:

<ifmodule mod_expires.c>
<filesmatch “\.(jpg|jpeg|gif|png|css|js)$”>
ExpiresActive on
ExpiresDefault “access plus 1 month”
</filesmatch>
</ifmodule>

3. File > Save As
4. In File name: field type .htaccess
5. Select All Files in Save as type: field
6. Click Save button

In the above example I have chosen to compress images (jpeg, jpg, gif and png, as well as external CSS and JavaScript files.

Caching of images is ideal because your basic web site template likely uses the same images across the whole site - these elements can be cached making page switching faster.

The server only needs to get the page text, and any additional on-page images, rather than a total refresh.

It isn’t advisable to add HTML or PHP to this, as the index.html or index.php file will be cached, even after you have refreshed it.

With this method I still have to rename my external CSS and JavaScript files if I make changes, however, this is unlikely/rare so for my needs caching these files is another way to make my pages load faster.

It is possible to choose the time period in the above code, ExpiresDefault “access plus 1 month”, this can be changed to 1 hour, 1 week, 1 year etc. Choose whichever is best for your needs.

Apart from 1 hour caching, the file name will need to be changed otherwise users may see an outdated version of your web site.

del.icio.usDigg itNewsvineRedditStumble Upon