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.
good i got what i wanted
ok man i will just link to your post sorry for that
sorry for that i have removed from my site
Pingback: klog » Blog Archive » efficient JS minification using PHP
You don’t need to calculate md5, you can simply use filemtime($file_url) instead – it’s much faster!
But yeah – I think in the first case, mtime is sufficient. You’re right.
If there are more files, you can use the biggest filemtime (eg. modified time of last changed file) and it’s allmost the same. 😉
But ms5 has an advantage: if you upload older version of the file, md5 is the same, and already cached my users browser.
M@ñ, this solution is most likely not for you. The solution I’ve posted above is specifically for PHP + Linux + Apache. You are probably using ASPX + Windows + IIS. Totally different environment.
You would have to get help from an experienced ASPX programmer.