简体   繁体   中英

How to automatically add version numbers of md5 hash to javascript and css files in Visual Studio or use another way to force browser cache refresh?

Whenever I put out a new version of CSS or javascript files for any of our web applications, I manually add a ?v=# to the URL in the head of the HTML (# is a version number, like 3 or 10) to make sure the users browser cache isn't standing in the way of the changes.

But some applications have multiple CSS and multiple JS files in the head and it is tedious to keep track of all changed files.

We use the ASP.NET platform on an IIS server, so using the answer to What is an elegant way to force browsers to reload cached CSS/JS files? is not possible but I am looking for something similar. Preferably all javascript.

I like the suggestion in that post to use a md5 hash but I cannot seem to find a way to calculate the checksum of a CSS or JS file.

The code would look something like this (using jQuery):

$.each($("script[type='text\javascript']"),function(){
    $(this).attr("src",$(this).attr("src") + "?v=" + checkMD5Sum($(this).attr("src")) );
});

function checkMD5Sum(url){
    //get the hash or something to auto version the file
    //I could send the url or filename to a webmethod to get the MD5 check sum, but doing this after page load is not usefull, so what to do?
}

Or perhaps using a postbuild process in Visual Studio, but I have never done that, so I am reluctant to try.


Edit

Going to try this in the web.config as per Adding Caching Profiles

<configuration>
   <system.webServer>
      <caching enabled="true">
         <profiles>
            <add extension=".js" policy="CacheUntilChange" />
            <add extension=".css" policy="CacheUntilChange" />
         </profiles>
      </caching>
   </system.webServer>
</configuration>

Your solution seems to require the browser to fetch the file twice, and you're given no guarantee of the state of the first fetch. So it doesn't work.

Caching is directed by the server. It's not possible to decide when a new version is available on the client - unless you ignore the cache and always fetch a fresh copy.

There are many ways to implement a caching policy. Fingerprinting with a version number is one of them.

I prefer to use ETag s. Have the ETag be the filemtime and you're good.

  VersionNumber = System.Configuration.ConfigurationManager.AppSettings["Version"];

    //Caching Issues For JS
    public static string JSVersionUpdate(string JsFile)
    {
        StringBuilder str = new StringBuilder();
        str.Append(GetQualifiedPath(JsFile));
        str.Append("?Version=");
        str.Append(VersionNumber);
        return str.ToString();
    }

    public static void DiscardVersion()
    {
        VersionNumber = null;
    }

    //get Full Path for JS File
    private static string GetQualifiedPath(string path)
    {
        var httpRequestBase = new System.Web.HttpContextWrapper(System.Web.HttpContext.Current);

        path = path.Replace("~", string.Empty);

        string appPath = string.Empty;
        if (httpRequestBase != null)
        {
            //Formatting the fully qualified website url/name
            appPath = string.Format("{0}://{1}{2}{3}{4}",
                        httpRequestBase.Request.Url.Scheme,
                        httpRequestBase.Request.Url.Host,
                        httpRequestBase.Request.Url.Port == 80 ? string.Empty : ":" + httpRequestBase.Request.Url.Port,
                        httpRequestBase.Request.ApplicationPath,
                        path);
        }
        appPath = appPath.TrimEnd('/');

        return appPath;
    } 
}

In UI Page : script src="JSVersionUpdate("~/Scripts/Application/Abc.js")"

O/p : ~/Scripts/Application/Abc.js/version=1.0

Browser request for JS Files from server only if Version is Different else it will cached out.Now i don't need to tell someone to clear the cache again and again after deployment.Only thing i do is i change Version Number in Web Config

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM