Force JavaScript file update without disabling caching


In a large-scale web application that I develop, there is an inconvenience every time there are updates, because browsers, especially Google Chrome, cache JavaScript files and, sometimes, there are incompatibilities between the server and client code, leading to to unforeseen situations and errors.

We have already considered versioning our JavaScript files so that their name carries the version number, making the browser consider them as new files, but this proved to be unfeasible due to the large amount of files that exist and the confusion this causes in our versioner (GIT).

Is there any pattern or solution that forces JavaScript to be reloaded every time it changes, without the user having to CTRL+F5 or clear the cache ? It is also not an option to disable caching of pages.



There is a technique called "Querystring Ghost" that solves this problem in most browsers.

In PHP it is done like this:

<link href="/file-css.css?<?php echo time(); ?>" type="text/css" />
<script type="text/javascript" src="/file-javascript.js?<?php echo time(); ?>"></script>


<link href="/file-css.css?1433981258" type="text/css" />
<script type="text/javascript" src="/file-javascript.js?1433981258"></script>

This generates a different URL on each "F5" and forces the browser to redownload the file.

This technique is used to not have to change the web server header settings.


The above solution can cause two problems:

1st) Increased internet traffic from the web server.
2nd) The web application loads slower because it doesn't use the browser cache benefits.

So to solve these two problems there are two solutions.

1st solution:

Create a constant that would update only when CSS and JS files change versions.


I put a constant in Web.config that indicates the version:

    <add key="Version" value="1254"/>

On Site.Master I put:

<link href="/file-css.css?<%= ConfigurationManager.AppSettings["Version"] %>" type="text/css" />
<script type="text/javascript" src="/file-javascript.js?<%= ConfigurationManager.AppSettings["Version"] %>"></script>


It is recommended that the constant "VERSION" be created in a file of the type "config.php". But I put it here just for demonstration:

define('VERSION', '1254');
<link href="/file-css.css?<?php echo VERSION; ?>" type="text/css" />
<script type="text/javascript" src="/file-javascript.js?<?php echo VERSION; ?>"></script>

Both programming languages ​​generate the same result in HTML:

<link href="/file-css.css?1254" type="text/css" />
<script type="text/javascript" src="/file-javascript.js?1254"></script>

2nd solution

Write the HTML itself, changing the numbering "1254" only when the CSS and JS files change versions.

This last solution I consider the easiest.

References: Prevent Your CSS and JavaScript Files From Being Cached

Scroll to Top