JHtml::script and JHtml::stylesheet have a cache busting technique that doesn't seem to be documented clearly. How do I go about using it?
1 Answer
Yes, there is a built-in cache busting technique. If you use it, your HTML will look like this:
<script src="/media/path/foo/bar.js?32af2f62db6e60053132340acc9dfb3c" type="text/javascript"></script>
How the cache busting technique works:
This works by appending a different series of characters in the URL query section every time that the file changes. This way, the browser won't have a cached entry for this never-before-seen URL, and will have to fetch it again. Joomla and your server are already configured to ignore the query part of the URL when it comes to serving static files.
How to implement it:
Here's how to use it:
JHtml::_("script", "path/foo/bar.js");
Or:
JHtml::_("stylesheet", "path/foo/bar.css");
(Note that using addStyleSheet
and addScript
does not work, you have to use JHtml::script
and JHtml::stylesheet
instead.)
Then, make sure that the directory that contains the file (path/foo
) contains a file named MD5SUM
(not MD5SUMS
). This file will contain the characters that will be appended to the URL with a ?
. It doesn't have to be an MD5SUM checksum, it could be anything, but the intent is that it does contain a checksum of the files in that directory. Sadly, there's no way to have a separate checksum for each file in that directory, if you want cache busting to work with this technique, the checksum has to change for all the files in that directory.
Here's how to create it on Linux on the command-line, you should probably add something like this in your build script if you have one:
cd path/foo
find . -maxdepth 1 -type f -not -name MD5SUM -exec md5sum "{}" ";" | sort | md5sum > MD5SUM
This creates the MD5SUM checksum of each file in that directory (except MD5SUM to avoid a feedback loop), and then MD5SUMs all of that output into one final MD5SUM
file.
(By default, the command md5sum
includes filenames and newlines, but it should still work regardless.)