Almost every time someone says to me that something I was working on is broken, the answer is “clear your cache”, and that automagically fixes everything. However, that’s not an ideal solution – ideally, the problem would never happen in the first place.
So, why does the problem happen?
Let’s say that there is a HTML file which calls a JS function like this:
showImage(); – the JS function is included from the external file
Browsers are usually set to cache .js files, and that’s the correct behaviour for the most part. Unfortunately, when a file needs to be fixed, it can cause problems.
For example, let’s say that I’ve corrected the function name to match my usual naming scheme –
So, how to get around this?
The solution I’m using at the moment involves a little bit of
mod_rewrite and PHP.
Sticking with the contrived example, let’s rewrite
/j/images.js so it is accessible from
ExpiresActive On ExpiresDefault A259200 RewriteEngine on RewriteRule ^j/images$ /j/images.js [L]
Now, we add a little magic. We want to change the URL if the file has changed. The only way to know this is to look at the modified date of the file.
In your PHP, you could do it like this:
and then change the
.htaccess file to allow that:
ExpiresActive On ExpiresDefault A259200 RewriteEngine on RewriteRule ^j/images/(.*)$ /j/images.js [L]
Now, if no file changes happen, then the MD5 hash (and therefore the URL) will be cacheable, and if the file changes, then the URL will automatically change as well.
…and that’s not all!
/j/js.php file. Here’s a short excerpt:
That’s then pointed to with this line in my .htaccess:
RewriteRule ^js/(.*)$ /j/js.php [L]
And it’s referenced in the browser like this:
Simple, innit! That simple trick now keeps track of a number of files, and the browser knows immediately if there are any changes.
BTW: The same trick can be used with images, css, and any number of other “static” objects.