Google Ads

December 3, 2017

Yet another HTML cache busting technique

If you are coding your web application or web site from the ground up then you may be already facing problems where changing individual files does not get reflected immediately. This is due to browsers caching some of the files to speed up loading performance and also to save bandwidths. The process of avoiding caching in the browsers is called cache busting.  There are already a ton of solutions out there which can be applied to your HTML code to avoid caching where some are tedious to maintain and others are a breeze. Although not very well known technique here I am presenting how to use hashing technique to do HTML cache busting. This technique can be well applied to both client side or server side scripting languages as well as using any cryptographic hash functions. The method I have selected for my web development is client side PHP scripting language and SHA-1 hash function. Using this method the following HTML code shows how to import external CSS file with cache busting feature:

<link rel="stylesheet" <?php echo "href=\"style1.css?v=" . sha1_file('style1.css') . "\"" ?>>

In the above code, PHP script will inject HREF attribute into the link tag. The ?v=" . sha1_file('style1.css') code fragment will change each time the CSS file is modified as well as add a argument to the CSS file name which will force browsers to load the CSS file. As the SHA-1 hash function is unique each time for a particular CSS file data set the above code works well as intended.

The following code snippet shows that the same technique can be applied to import JavaScript files with cache busting feature:

<script <?php echo "src=\"load.js?v=" . sha1_file('load.js') . "\"" ?>></script>


No comments:

Post a Comment