Did you notice that after updating your CSS, JavaScript, or image files, your browser fails to show you the updated content?

The reason is that web browsers store the data after it successfully loaded the web page. The second time a web page is loaded; it will get the data from its cache, not from the server.

How Cache Works

Caching is a way to speed up user browsing experience by storing the information that was already viewed into the browser’s cache. There is no need to re-download the original file from the server; instead, the browser will just show the saved file from its cache.

Cache Busting

Cache busting is a way to force the web browser to show or re-download the original file from the server.

Cache busting is only necessary if you do frequent changes into a file. An example of these file type is CSS file.

Normally, we do embed a CSS file like this:

<link rel="stylesheet" media="screen" href="style.css" />

If you do changes to that file, the user who already viewed the older version of the file will not see the updated version. We need to tell the browser that the file is already updated by adding some query string into the file URL.

You can add random numbers, alphanumeric, names, or whatever you want as long as it changes after updating the file at the end of the file URL.

By using rand() PHP function, the new embed code will be:

<link rel="stylesheet" media="screen" href="style.css?ver=<?php echo rand(); ?>" />

Or by using filemtime() PHP function:

<link rel="stylesheet" media="screen" href="style.css?ver=<?php echo filemtime('style.css'); ?>" />

This will result like:

<link rel="stylesheet" media="screen" href="style.css?ver=15632" />

You can apply the same method to images, JavaScript, and other file types

<script type="text/javascript" src="script.js?ver=<?php echo rand(); ?>"></script>

<img src="image.jpg?ver=<?php echo rand(); ?>" alt="image name" />