1158

I have noticed that some browsers (in particular, Firefox and Opera) are very zealous in using cached copies of .css and .js files, even between browser sessions. This leads to a problem when you update one of these files, but the user's browser keeps on using the cached copy.

What is the most elegant way of forcing the user's browser to reload the file when it has changed?

Ideally, the solution would not force the browser to reload the file on every visit to the page.


I have found John Millikin's and da5id's suggestion to be useful. It turns out there is a term for this: auto-versioning.

I have posted a new answer below which is a combination of my original solution and John's suggestion.

Another idea that was suggested by SCdF would be to append a bogus query string to the file. (Some Python code, to automatically use the timestamp as a bogus query string, was submitted by pi..)

However, there is some discussion as to whether or not the browser would cache a file with a query string. (Remember, we want the browser to cache the file and use it on future visits. We only want it to fetch the file again when it has changed.)

6
  • I have this in my .htaccess, and never any problems with cached files: ExpiresActive On ExpiresDefault "modification". May 15, 2014 at 14:06
  • 2
    I'd definitely agree that adding versioning info to the file's URL is by far the best way to go. It works, all the time, for everyone. But, if you're not using it, and you just need to reload that one CSS or JS file occasionally in your own browser... just open it in its own tab and hit SHIFT-reload (or CTRL-F5)! You can do effectively the same thing using JS by loading a file in a (hidden) iframe, waiting till it loads, and then calling iframe.contentWindow.location.reload(true). See method (4) of stackoverflow.com/a/22429796/999120 - that's about images, but the same applies.
    – Doin
    Dec 27, 2015 at 5:17
  • 8
    I really appreciate the way this question was asked and has been updated since then. It completely described what I should expect in the answers. I am going to follow this approach in my questions from now on. Cheers!
    – rd22
    Aug 1, 2016 at 9:46
  • 2
    For reference: da5id's's deleted answer is "If an update is big/important enough I generally change the name of the file.". Nov 28, 2020 at 3:48
  • If the changes are not very often, I have a suggestion. Just change the file name and edit the source code to include the new file name. Then there’s no cached file for the browser to read. Feb 24, 2021 at 10:00

58 Answers 58

1
2
2

I suggest implementing the following process:

  • version your CSS and JavaScript files whenever you deploy. Something like: screen.1233.css (the number can be your SVN revision if you use a versioning system)

  • minify them to optimize loading times

2

TomA's answer is right.

Using the "querystring" method will not be cached as quoted by Steve Souders below:

...that Squid, a popular proxy, doesn’t cache resources with a querystring.

TomA's suggestion of using style.TIMESTAMP.css is good, but MD5 would be much better as only when the contents were genuinely changed, the MD5 changes as well.

2
  • also, using a timestamp as a querystring param would force the reload of the file every single time, meaning no caching at all
    – Luca
    Oct 10, 2012 at 23:40
  • 2
    A 2008 comment in that same blog post mentions that Squid's defaults have changed; the question is what percentage of your traffic is handled by (now) obsolete versions of Squid.
    – TomG
    Nov 6, 2013 at 15:59
2

I see a problem with the approach of using a timestamp- or hash-based differentiator in the resource URL which gets stripped out on request at the server. The page that contains the link to e.g. the style sheet might get cached as well. So the cached page might request an older version of the style sheet, but it will be served the latest version, which might or might not work with the requesting page.

To fix this, you either have to guard the requesting page with a no-cache header or meta, to make sure it gets refreshed on every load. Or you have to maintain all versions of the style file that you ever deployed on the server, each as an individual file and with their differentiator intact so that the requesting page can get at the version of the style file it was designed for. In the latter case, you basically tie the versions of the HTML page and the style sheet together, which can be done statically and doesn't require any server logic.

2

For a Java Servlet environment, you can look at the Jawr library. The features page explains how it handles caching:

Jawr will try its best to force your clients to cache the resources. If a browser asks if a file changed, a 304 (not modified) header is sent back with no content. On the other hand, with Jawr you will be 100% sure that new versions of your bundles are downloaded by all clients. Every URL to your resources will include an automatically generated, content-based prefix that changes automatically whenever a resource is updated. Once you deploy a new version, the URL to the bundle will change as well so it will be impossible that a client uses an older, cached version.

The library also does JavaScript and CSS minification, but you can turn that off if you don't want it.

2

A SilverStripe-specific answer worked out from reading: http://api.silverstripe.org/3.0/source-class-SS_Datetime.html#98-110:

Hopefully this will help someone using a SilverStripe template and trying to force reload a cached image on each page visit / refresh. In my case it is a GIF animation which only plays once and therefore did not replay after it was cached. In my template I simply added:

?$Now.Format(dmYHis)

to the end of the file path to create a unique time stamp and to force the browser to treat it as a new file.

1
  • The api.silverstripe.org link is broken (404). Nov 28, 2020 at 5:02
2

Disable caching of script.js only for local development in pure JavaScript.

It injects a random script.js?wizardry=1231234 and blocks regular script.js:

<script type="text/javascript">
  if(document.location.href.indexOf('localhost') !== -1) {
    const scr = document.createElement('script');
    document.setAttribute('type', 'text/javascript');
    document.setAttribute('src', 'scripts.js' + '?wizardry=' + Math.random());
    document.head.appendChild(scr);
    document.write('<script type="application/x-suppress">'); // prevent next script(from other SO answer)
  }
</script>

<script type="text/javascript" src="scripts.js">
2

One of the best and quickest approaches I know is to change the name of the folder where you have CSS or JavaScript files.

Or for developers: Change the name of your CSS and JavaScript files something like versions.

<link rel="stylesheet" href="cssfolder/somecssfile-ver-1.css"/>

Do the same for your JavaScript files.

1
  • we can pass version in query string to make URL uniq. rather than changing filename Apr 18, 2022 at 10:50
2

I put an MD5 hash of the file's contents in its URL. That way I can set a very long expiration date, and don't have to worry about users having old JS or CSS.

I also calculate this once per file at runtime (or on file system changes) so there's nothing funny to do at design time or during the build process.

If you're using ASP.NET MVC then you can check out the code in my other answer here.

1

"Another idea which was suggested by SCdF would be to append a bogus query string to the file. (Some Python code to automatically use the timestamp as a bogus query string was submitted by pi.) However, there is some discussion as to whether or not the browser would cache a file with a query string. (Remember, we want the browser to cache the file and use it on future visits. We only want it to fetch the file again when it has changed.) Since it is not clear what happens with a bogus query string, I am not accepting that answer."

<link rel="stylesheet" href="file.css?<?=hash_hmac('sha1', session_id(), md5_file("file.css")); ?>" />

Hashing the file means when it has changed, the query string will have changed. If it hasn't, it will remain the same. Each session forces a reload too.

Optionally, you can also use rewrites to cause the browser to think it's a new URI.

1

Another suggestion for ASP.NET websites,

  1. Set different cache-control:max-age values, for different static files.

  2. For CSS and JavaScript files, the chances of modifying these files on server is high, so set a minimal cache-control:max-age value of 1 or 2 minutes or something that meets your need.

  3. For images, set a far date as the cache-control:max-age value, say 360 days.

  4. By doing so, when we make the first request, all static contents are downloaded to client machine with a 200-OK response.

  5. On subsequent requests and after two minutes, we see 304-Not Modified requests on CSS and JavaScript files which avoids us from CSS and JavaScript versioning.

  6. Image files will not be requested as they will be used from cached memory till the cache expires.

  7. By using the below web.config configurations, we can achieve the above described behavior,

    <system.webServer>
        <modules runAllManagedModulesForAllRequests="true"/>
        <staticContent>
            <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="00.00:01:00"/>
        </staticContent>
        <httpProtocol>
            <customHeaders>
                <add name="ETAG" value=""/>
            </customHeaders>
        </httpProtocol>
    </system.webServer>
    
    <location path="Images">
        <system.webServer>
            <staticContent>
                <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="180.00:00:00" />
            </staticContent>
        </system.webServer>
    </location>
    
1

If you are using a modern browser, you could use a manifest file to inform the browsers which files need to be updated. This requires no headers, no versions in URLs, etc.

For more details, see: Using the application cache

1

Many answers here advocate adding a timestamp to the URL. Unless you are modifying your production files directly, the file's timestamp is not likely to reflect the time when a file was changed. In most cases this will cause the URL to change more frequently than the file itself. This is why you should use a fast hash of the file's contents such as MD5 as levik and others have suggested.

Keep in mind that the value should be calculated once at build or run, rather than each time the file is requested.

As an example, here's a simple bash script that reads a list of filenames from standard input and writes a JSON file containing hashes to standard output:

#!/bin/bash
# Create a JSON map from filenames to MD5 hashes
# Run as hashes.sh < inputfile.list > outputfile.json

echo "{"
delim=""
while read l; do
    echo "$delim\"$l\": \"`md5 -q $l`\""
    delim=","
done
echo "}"

This file could then be loaded at server startup and referenced instead of reading the file system.

1

I came to this question when looking for a solution for my SPA, which only has a single index.html file listing all the necessary files. While I got some leads that helped me, I could not find a quick-and-easy solution.

In the end, I wrote a quick page (including all of the code) necessary to autoversion an HTML/JavaScript index.html file as part of the publishing process. It works perfectly and only updates new files based on date last modified.

You can see my post at Autoversion your SPA index.html. There is a stand-alone Windows application there too.

The guts of the code is:

private void ParseIndex(string inFile, string addPath, string outFile)
{
    string path = Path.GetDirectoryName(inFile);
    HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument();
    document.Load(inFile);

    foreach (HtmlNode link in document.DocumentNode.Descendants("script"))
    {
        if (link.Attributes["src"]!=null)
        {
            resetQueryString(path, addPath, link, "src");
        }
    }

    foreach (HtmlNode link in document.DocumentNode.Descendants("link"))
    {
        if (link.Attributes["href"] != null && link.Attributes["type"] != null)
        {
            if (link.Attributes["type"].Value == "text/css" || link.Attributes["type"].Value == "text/html")
            {
                resetQueryString(path, addPath, link, "href");
            }
        }
    }

    document.Save(outFile);
    MessageBox.Show("Your file has been processed.", "Autoversion complete");
}

private void resetQueryString(string path, string addPath, HtmlNode link, string attrType)
{
    string currFileName = link.Attributes[attrType].Value;

    string uripath = currFileName;
    if (currFileName.Contains('?'))
        uripath = currFileName.Substring(0, currFileName.IndexOf('?'));
    string baseFile = Path.Combine(path, uripath);
    if (!File.Exists(baseFile))
        baseFile = Path.Combine(addPath, uripath);
    if (!File.Exists(baseFile))
        return;
    DateTime lastModified = System.IO.File.GetLastWriteTime(baseFile);
    link.Attributes[attrType].Value = uripath + "?v=" + lastModified.ToString("yyyyMMddhhmm");
}
1

Small improvement from existing answers...

Using a random number or session id would cause it to reload on each request. Ideally, we may need to change only if some code changes were done in any JavaScript or CSS file.

When using a common JSP file as a template to many other JSP and JavaScript files, add the below in a common JSP file

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<c:set var = "version" scope = "application" value = "1.0.0" />

Now use the above variable in all locations as below in your JavaScript file inclusions.

<script src='<spring:url value="/js/myChangedFile.js?version=${version}"/>'></script>

Advantages:

  1. This approach will help you in changing version number at one location only.
  1. Maintaining a proper version number (usually build/release number) will help you to check/verify your code changes being deployed properly (from developer console of the browser).

Another useful tip:

If you are using the Chrome browser, you can disable caching when Dev Tools is open. In Chrome, hit F12F1 and scroll to SettingsPreferencesNetwork → *Disable caching (while DevTools is open)

Chrome DevTools

0
1

A simple solution for static files (just for development purposes) that adds a random version number to the script URI, using script tag injections

<script>
    var script = document.createElement('script');
    script.src = "js/app.js?v=" + Math.random();
    document.getElementsByTagName('head')[0].appendChild(script);
</script>
1

In ASP.NET Core you could achieve this by adding 'asp-append-version':

<link rel="stylesheet" href="~/css/xxx.css" asp-append-version="true" />

 <script src="~/js/xxx.js" asp-append-version="true"></script>

It will generate HTML:

<link rel="stylesheet" href="/css/xxx.css?v=rwgRWCjxemznsx7wgNx5PbMO1EictA4Dd0SjiW0S90g" />

The framework will generate a new version number every time you update the file.

1

If you don't want the client to cache the file ever, this solution seems to be quickest to implement. Adjust the part with time() if you e.g. load the file in footer.php:

<script src="<?php echo get_template_directory_uri(); ?>/js/main.js?v=<?= time() ?>"></script>
0

My method to do this is simply to have the link element into a server-side include:

<!--#include virtual="/includes/css-element.txt"-->

where the contents of css-element.txt is

<link rel="stylesheet" href="mycss.css"/>

so the day you want to link to my-new-css.css or whatever, you just change the include.

0
0

Well, I have made it work my way by changing the JavaScript file version each time the page loads by adding a random number to JavaScript file version as follows:

// Add it to the top of the page
<?php
    srand();
    $random_number = rand();
?>

Then apply the random number to the JavaScript version as follow:

<script src="file.js?version=<?php echo $random_number;?>"></script>
2
  • 6
    That's a pretty bad idea. This means that the user has to re-download the file on every single page load. Caching is a good thing--this question is about how to utilize caching when you want to, but not when you don't.
    – Kip
    Aug 22, 2016 at 1:20
  • Yea, the user has to re-download the file on every single page load because some java script included under (iframe) doesn't update page content unless the user press F5 or reload the page manually. So this is the best solution to reload the content each time when a new visitor visiting the website.
    – Mizo Games
    Aug 23, 2016 at 21:47
0

We have one solution with some different way for implementation. We use the above solution for it.

datatables?v=1

We can handle the version of the file. It means that every time that we change our file, change the version of it too. But it's not a suitable way.

Another way used a GUID. It wasn't suitable either, because each time it fetches the file and doesn't use from the browser cache.

datatables?v=Guid.NewGuid()

The last way that is the best way is:

When a file change occurs, change the version too. Check the follow code:

<script src="~/scripts/[email protected](Server.MapPath("/scripts/main.js")).ToString("yyyyMMddHHmmss")"></script>

By this way, when you change the file, LastWriteTime change too, so the version of the file will change and in the next when you open the browser, it detects a new file and fetch it.

0

Here is my Bash script-based cache busting solution:

  1. I assume you have CSS and JavaScript files referenced in your index.html file
  2. Add a timestamp as a parameter for .js and .css in index.html as below (one time only)
  3. Create a timestamp.txt file with the above timestamp.
  4. After any update to .css or .js file, just run the below .sh script

Sample index.html entries for .js and .css with a timestamp:

<link rel="stylesheet" href="bla_bla.css?v=my_timestamp">
<script src="scripts/bla_bla.js?v=my_timestamp"></script>

File timestamp.txt should only contain same timestamp 'my_timestamp' (will be searched for and replaced by script later on)

Finally here is the script (let's call it cache_buster.sh :D)

old_timestamp=$(cat timestamp.txt)
current_timestamp=$(date +%s)
sed -i -e "s/$old_timestamp/$current_timestamp/g" index.html
echo "$current_timestamp" >timestamp.txt

(Visual Studio Code users) you can put this script in a hook, so it gets called each time a file is saved in your workspace.

0

I've solved this issue by using ETag:

ETag or entity tag is part of HTTP, the protocol for the World Wide Web. It is one of several mechanisms that HTTP provides for Web cache validation, which allows a client to make conditional requests. This allows caches to be more efficient and saves bandwidth, as a Web server does not need to send a full response if the content has not changed. ETags can also be used for optimistic concurrency control,1 as a way to help prevent simultaneous updates of a resource from overwriting each other.

  • I am running a Single-Page Application (written in Vue.JS).
  • The output of the application is built by npm, and is stored as dist folder (the important file is: dist/static/js/app.my_rand.js)
  • Nginx is responsible of serving the content in this dist folder, and it generates a new Etag value, which is some kind of a fingerprint, based on the modification time and the content of the dist folder. Thus when the resource changes, a new Etag value is generated.
  • When the browser requests the resource, a comparison between the request headers and the stored Etag, can determine if the two representations of the resource are the same, and could be served from cache or a new response with a new Etag needs to be served.
1
  • Can you elaborate a little bit? Right now it is effectively a link-only answer. Nov 28, 2020 at 8:19
0
location.reload(true)

Or use "Network" from the inspector ([CTRL] + [I]), click "disable cache", click trash icon, click "load"/"get"

0

I use the following solution for the described problem. Instead of supplying js and css as separate files, their content simply get inserted in a web page content. It can be done manually, or completely transparent and automatic. It's implemented using a feature of the proprietary framework I use for a page generation. However, a similar functionality should be supported by any good framework. For example:

.....
<script type="text/javascript" src="js/tinysort.js"></script>
<script type="text/javascript" src="js/webfolder.js"></script>
<script type="text/javascript" src="js/ui.js"></script>
<div style="padding-bottom:3px;padding-top:3px"><h3 style="display:inline">
....

Will look in the final web assembly as:

....
<script>
  // from tinysort.js 
  var TINY={};

  function T$(i){return document.getElementById(i)}
  function T$$(e,p){return p.getElementsByTagName(e)}
  ....
  // from webfolder.js
  function selectAll() {
   if (document.forms.folder.elements.files.length == undefined)
      document.forms.folder.elements.files.checked = document.forms.folder.elements.files.checked == false;
   else  
     for(var el=0 ...
  .....
</script>
<div style="padding-bottom:3px;padding-top:3px"><h3 style="display:inline">
....

You shouldn't worry that a web page becomes huge, all this content will be loaded by a browser anyway. Some parallelism in loading doesn't make sense when http 2 is used. As only parts of js or css code get completely debugged, they can be separated back. A version number gets propagated in the file name itself to avoid using old code. The above approach works well for SPA which I use most a recent time.

-1

If you are using jQuery, there is an option called cache that will append a random number.

This is not a complete answer I know, but it might save you some time.

-2

Another way for JavaScript files would be to use the jQuery $.getScript in conjunction with $.ajaxSetup option cache: false.

Instead of:

<script src="scripts/app.js"></script>

You can use:

$.ajaxSetup({
  cache: false
});

$.getScript('scripts/app.js'); // GET scripts/app.js?_1391722802668
1
  • the idea isn't to prevent caching altogether. you just want the user to get the latest file as soon as the file is modified.
    – Kip
    Feb 6, 2014 at 22:18
-3

Changing the filename will work. But that's not usually the simplest solution.

An HTTP cache-control header of 'no-cache' doesn't always work, as you've noticed. The HTTP 1.1 spec allows wiggle-room for user-agents to decide whether or not to request a new copy. (It's non-intuitive if you just look at the names of the directives. Go read the actual HTTP 1.1 spec for cache... it makes a little more sense in context.)

In a nutshell, if you want iron-tight cache-control use

Cache-Control: no-cache, no-store, must-revalidate

in your response headers.

3
  • 1
    Problem with this approach is that it generates a round trip to the server for all such content. This is not good. Sep 23, 2008 at 8:14
  • This solution isn't perfect but it works for all situations, including static web pages. And if you are only doing this for a limited number of files, say your CSS files, then it shouldn't add a significant amount of time to the page load.
    – Bill
    Oct 5, 2008 at 15:16
  • The first sentence may refer to da5id's's deleted answer -"If an update is big/important enough I generally change the name of the file.". Nov 28, 2020 at 3:50
-3

The simplest method is to take advantage of the PHP file read functionality. Just have the PHP echo the contents of the file into tags.

<?php
//Replace the 'style.css' with the link to the stylesheet.
echo "<style type='text/css'>".file_get_contents('style.css')."</style>";
?>

If you're using something besides PHP, there are some variations depending on the language, but almost all languages have a way to print the contents of a file. Put it in the right location (in the section), and that way, you don't have to rely on the browser.

1
  • 7
    Problem with this is you lose the ability to cache the file, making the experience slower for the user.
    – Austin
    Nov 3, 2011 at 18:10
1
2

Not the answer you're looking for? Browse other questions tagged or ask your own question.