Cache Components As Long As Possible
The best way to improve performance of an action is to not perform the action. Zero sounds like a great performance measurement! When it comes to the journey a response makes from a server to a client, the best possible performance is to eliminate the journey completely.
A web page consists of many components: the HTML, CSS, JavaScript, various types of media, and others. Each component has to make the journey from the server to the client. Or does it? If the component hasn’t changed since the last time it made the trip, why make the trip a second time? Why can’t the browser just use the component it got last time?
If the browser would be so kind as to store the component locally, it could reuse that component in the future instead of downloading it again. In fact, browsers can do this. All they need to know is how long to cache the component before re-requesting it from the server. The browser cannot be expected to know when the component changes, so the server has to tell it. This caching process happens on the client’s machine, but is under the server’s control.
HTML caching is inappropriate if the page changes dynamically or frequently. It also interferes with page statistics because it hides user hits from the server. For these reasons, it is often more appropriate to make the HTML non-cacheable and to place all cacheable components in external files.
How To Implement HTML Caching
Server-side scripting languages (e.g., PHP, ASP) provide a way to set headers for the current HTML page. Use it to include either the expires or cache-control: max-age header line. Expires allows us to set an expiry date; cache-control: max-age allows us to set a duration (length of time from access date to expiry date).
How To Implement Other Caching
Apache’s ExpiresDefault and ExpiresByType directives can be used within .htaccess files to set the expiry dates. For example:
ExpiresActive On ExpiresByType image/gif "access plus 1 year" ExpiresByType application/ecmascript M86400 ExpiresDefault A3600
In this example, the first line turns cache control on (a necessary first step), the second line sets GIF images served from this directory to expire one year after the browser accesses them, the third line sets JavaScripts served from this directory to expire 24 hours after they were last modified, and the fourth line sets other data served from this directory to expire one hour after they are accessed.
Keep in mind that .htaccess applies to the directory it is in and to all subdirectories below it.