Prevent browser cache from CSS, JS, and image files

In this article, I am going to teach you, how you can prevent the browser cache from keep displaying the old content. We will ask the browser to update your cached files and fetch the fresh content. Suppose, you have written a Javascript file named “script.js”. Now, you added some functionality code in that file, or change the algorithm of some function. You have updated the file on a live server. But your changes will not affect your user’s side if their browser has cached that JS file.

How browser cache works

In that case, you have to forcefully tell the browser to fetch the updated file instead of serving the cached file. The browser cache works in such a manner that, whenever a CSS, JS, or image file is rendered in the client’s browser, the browser stores the URL of that file in its cache along with its content. When the user refreshes the page, all <style>, <script> and <img /> tags request the resources using the “href” and “src” attribute. The browser checks if the requested URL already exists in its cache database. If “yes” then it (browser) fetches its content from the cache database and serves it.

That’s why most of the time your website users are not able to view the updated content. As you now know the problem, you now have a solution. The browser searches the URL in its cache database. So, whenever you update your file, simply change the URL by appending a query parameter at the end of the URL. For example, if you have an image tag which is displaying an image named “1.jpg”, like this:

<img src="1.jpg" />

Skip cache and fetch fresh content

Now, you have replaced the “1.jpg” image with a new image and you want the user’s to view the new image, then simply change the URL like this:

<img src="1.jpg?v=1" />

Here, “v” stands for “version” but you can use any parameter you want. Make sure to append it with “?” so it will be treated as a parameter. Its sole purpose is to tell the browser that the URL has now changed. So, it must fetch the updated resource instead of from the cache database. Now, every time you change the image file, simply increment this version value like “?v=2” and the image will be updated for all users next time they refresh the page.

If you want the browser to never cache a specific resource, for example, you want the web browser to always serve the updated “1.jpg” file. In that case, append the PHP timestamp in the query parameter. A PHP timestamp is the number of seconds passed from the 1st of January 1970 till the current time.

<img src="1.jpg?v=<?php echo time(); ?>" />

This will prevent the browser to never cache this image. Because every time user sends a request for this resource, the URL will change each time.

See this in action