• Home
  • CSS
  • How to always load latest version of your CSS stylesheet or JavaScript file

How to always load latest version of your CSS stylesheet or JavaScript file

In today’s web development world, especially if we have a continuous project that we constantly update and add stuff to, we usually have a development and production versions of the website (commonly located on different servers with identical configuration). We perform fixes and add new features on development server first, test it, and then transfer all changes to the live (production) server for the site visitors to enjoy and take advantage of. Here comes the tricky part, which leads us to one of the most common user-related “issues” – cached CSS and JavaScript files. Imagine that you made some intensive changes to your CSS or JS file, tested it in your browser by hard-refreshing the pages (because you know that your CSS and JS are being cached by the browser), everything looked good, so you uploaded it to your production server. Now, how many end-users know how to hard-refresh the page if something doesn’t look right? You know it – very few. In this short manual I will explain one trick that will save you time trying to explain to your customer that he/she has to “hard-refresh the page to update cached CSS file. Please press CTRL+F5 :)”. Please note that your CSS/JS files will still be cached (your browser will not request them every time you load the site), however if your local cached version will not match the one currently on the server, it will request it from the server and will replace the local cached version with the most recent one. 1. In your .htaccess file (create one in the root folder of your site if you don’t have one yet), add the following line:
RewriteRule ^(.*)\.[\d]{10}\.(css|js)$ $1.$2 [L]
2. In your PHP header (where you declare your CSS and JS files), replace this line:
<link href="/css/style.css" rel="stylesheet" type="text/css" />
<link href="<?=auto_version('/css/style.css'); ?>" rel="stylesheet" type="text/css" />
Do the same thing for the rest of the files you want to auto-update. 3. Finally, BEFORE the line you just added to your header.php, declare this function below:
function auto_version($file) {
    if(strpos($file, '/') !== 0 || !file_exists($_SERVER['DOCUMENT_ROOT'] . $file))
        return $file;
    $mtime = filemtime($_SERVER['DOCUMENT_ROOT'] . $file);
    return preg_replace('{\\.([^./]+)$}', ".$mtime.\$1", $file);
That’s it. Now you don’t have to worry about your client calling you every time you update your CSS and/or JavaScript files.