How to auto-refresh cached CSS and JavaScript

How to easily make browsers re-download resources when they are updated, and avoid loading outdated cached versions.

1373 views

Edited: 2017-03-26 16:02

When editing static JavaScript and CSS files with caching enabled, browsers typically do not pick up the changes, and will instead load the cached version. This can cause errors with the layout for users, and confusion for the developers working on the files.

A solution to the problem is to append a version number to the files in a URL parameter. In PHP, we could simply get the time when the content of a file was last changed, and then use this as a URL parameter value.

$template_css_file = '/css/general.css';
$template_css_file = $template_css_file . '?v=' . filemtime($_SERVER["DOCUMENT_ROOT"] . $template_css_file);

The time when the file was last modified can be returned with the filemtime function, if for some reason the function fails, false will be returned instead of a timestamp.

The URL parameter is automatically updated whenever you edit the file, this will make browsers look at the file as a different file, and re-download the file instead of loading the outdated cached copy.

Dynamic content

There is a similar problem with dynamic content, but this is perhaps best solved by manually updating the cache when the source is modified, as checking for file changes in each .php file can be very resource heavy, especially if done on every request.

If you do plan on adding a file-check for dynamic files, you should look into the use of the Etag header, and avoid performing the check on every request.

Tell us what you think: