Articles

How to Enable Browser Caching

You can configure an app so that the browser will cache files it downloads from your server. When a response is cached, the browser will not request the file again for a period of time. Instead, it will use the same file it previously downloaded. This can speed up apps by decreasing the time it takes for the browser to load all of the resources a page uses, such as scripts, images, and stylesheets.

How Browser Caching Works

Browser caching works by having the HTTP response include an additional header that tells the browser the time and date after which the response will be considered stale.

For example, a response header such as:

Expires: Thu, 05 Apr 2063 12:00:00 GMT

tells the browser to not request the file again until April 2063.

Risks of Browser Caching

Browser caching does have downsides. If you change the content of a page, script, stylesheet, or image, any visitor who has recently been to your site may be using a cached version on the next visit to your site.

For example, if you change a stylesheet but you've told browsers to cache the previous version of the stylesheet, then your website may appear broken to some users because they are using the old stylesheet.

When you're using browser caching, the only way to ensure a user sees the most recent version of a changed file is to change the name of the files. Be careful with browser caching!

How to Use Browser Caching

You can add the following to your app's .htaccess file to, for example, set a default browser cache expiration of 300 seconds and a longer 3600 second expiration for CSS files:

ExpiresActive On
ExpiresDefault A300
ExpiresByType text/css A3600

Using the above syntax, the web server will calculate the correct date for the Expires header and will add that Expires header to the response.

For more information on available options for expires headers, see the Apache mod_expires documentation.