Hosting
Green web hosting packagesTutorials
Beginners guides to SEO & hostingBeginners guide to Web Hosting
Making browsers cache your content
In the previous section we suggested that you should put all the CSS for your site in one file and all the scripts for your site in another file. The reason for this is that if you can get the visitor’s browser to cache (remember) these files then it will only have to download CSS and Script files once however many pages your visitors go to. In addition, unless the visitor wipes out their browser cache, the next time they visit your site even months later the CSS and Script files will not need to be downloaded.
Browser cache – When a file is downloaded by the browser it will cache the page, at least until the browser is closed. It will not generally try to remember beyond this point as web pages change and it does not want to serve the visitor old content. This is fine for your html files (especially if they change regularly) but how about all the other files such as CSS or HTML? What if the CSS file, instead of /mystyles.css was called /mystyles210310.css (with the date appended to the back of the file name)- the browser could keep this for as long as it liked and when we wanted to change the CSS we just create a new file with a new date and link the new one in our html. The same goes for script files, just append the date on the back and assume that the file stays the same forever.
Time to live directives – So after making CSS and Script files with the date appended we should tell the browser how long to keep it for… and make it far into the future like 3 years! I can tell you how to do this on an Apache web server but if you are using a different kind of web server you will have to research this yourself.
Apache expiration date directive – To deliver a far-future expiration date in Apache you will have to alter (or create) a file called .htaccess in the sites html home directory of your web server. The .htaccess file tells Apache differences of behaviour that you would like applied to a particular directory compared with the default settings for the entire web server. Add this code:
<FilesMatch “\.(ico|pdf|flv|js|css|swf)$”>
ExpiresActive On
ExpiresDefault A29030400
Header append Cache-Control “public”
</FilesMatch>
This is roughly telling Apache to keep all files with endings ico,pdf,flv,js,css or swf in cache for 3 years.
A note for people that have complete control over their server: if you add a similar directive into the httpd.conf file it will apply this for all sites. In addition, it will eliminate the processing time taken to parse and implement the .htaccess file for each request which also takes a little time! After changing httpd.conf you will need to restart Apache but you need not do this is you are simply changing .htaccess.
Next section: Compressing text based content
Index of all our tutorials: Wight Hat tutorials