A Simple Way to Update CSS, JS & Image Browser  Cache

Clear The Google Chrome Browser CacheBrowser cache can speed up a website tremendously, but it can also cause web development headaches in the process. Have you ever uploaded a modified image, stylesheet or JavaScript file only to find that an out of date version is loading for the majority of your users?

This can quickly snowball into a usability nightmare. Fortunately there is a simple way to solve the issue using this PHP auto versioning function. This is a modified version of a concept posted by Kip on StackOverflow).

Add This to Your .htaccess File

# JS/CSS auto-versioning rewrites
RewriteEngine on
RewriteRule ^(.*)\.[\d]{10}\.(css|js)$ $1.$2 [L]

After that you’ll need to add the following PHP function to a global include file in your website or application. If you’re using WordPress this could be the functions.php file in your theme. If you’re using another system be sure this loads in a file you include on every page of your website at a point before you use the function.

The Auto Versioning PHP Function

/**
 *  Given a file, i.e. /css/base.css, replaces it with a string containing the
 *  file's mtime, i.e. /css/base.1221534296.css.
 *  
 *  @param $file  The file to be loaded.  Must be an absolute or URI path (i.e.
 *                starting with slash).
 */
function base_auto_version( $file ) {
	$current_url = ( isset($_SERVER['HTTPS']) && !empty( $_SERVER['HTTPS']) ) ? 'https://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'] : 'https://' . $_SERVER['SERVER_NAME'] . str_replace( '/', '', $_SERVER['REQUEST_URI'] );

	$local_file = ( strpos($file, 'http') == 0 ) ? str_replace( $current_url, '', $file ) : $file;
		
	if( strpos($local_file, '/') !== 0 || !file_exists($_SERVER['DOCUMENT_ROOT'] . $local_file) )
		return $local_file;
	
	$mtime = filemtime( $_SERVER['DOCUMENT_ROOT'] . $local_file );
	
	return preg_replace( '{\\.([^./]+)$}', ".$mtime.\$1", $local_file );
}

This function will accept absolute or full URI links to your files. For example, https://www.yourdomain.com/css/style.css and /css/style.css will both work with this function.

Autoversion Your CSS, JS & Image Files

In your website or application replace the src and href attributes of the <script> & <link> tags you want to auto-version. For example:

When you make changes to a file the auto version function will automatically rename your file to something like:

This ensures that all visitors, regardless of the browser they are using, will load the latest version of your CSS, JS & images. Hopefully this helps you and your website visitors avoid frustration after your next design update is rolled out.

Meet the Author

Kevin Leary, WordPress Consultant

I'm a custom WordPress web developer and analytics consultant in Boston, MA with 17 years of experience building websites and applications. View a portfolio of my work or request an estimate for your next project.