So I'm building a web app using C#.NET, and would like to add a version number to file references. For example:
<script src="mysite/scripts/default.123.js"></script>
Each time I modify files in the web app, including cshtml, CSS, JS, or images, is it possible to have that version number incremented dynamically? In other words, how do I get [or create] the version number in the first place? Is it possible?
This is to avoid caching old copies on the client browsers, especially when being served via XHR. For reasons I don't want to take the time to explain, I am NOT asking for alternative methods, such as dummmy parameters, no-cache meta tags, datetimestamps, CDN's etc.
I'd like this number to correspond to the most recent version of file that was modified - maybe "build version" isn't the right word. As Kyle Trauberman, assemblyversion might might work. However will this accomodate for changes to static resources, such as HTML or CSS? What is a good method for that?
<< is the left shift operator. It is shifting the number 1 to the left 0 bits, which is equivalent to the number 1 .
%d is a format specifier, used in C Language. Now a format specifier is indicated by a % (percentage symbol) before the letter describing it. In simple words, a format specifier tells us the type of data to store and print. Now, %d represents the signed decimal integer.
To solve this problem, I go with a slightly different approach. Rather than using a "version number", I simply append the last modified date. To make things convenient, I wrote a helper method:
public static HtmlString Script<T>(this HtmlHelper<T> html, string path)
{
var file = html.ViewContext.HttpContext.Server.MapPath(path);
DateTime lastModified = File.GetLastWriteTime(file);
TagBuilder builder = new TagBuilder("script");
builder.Attributes["src"] = path + "?modified=" + lastModified.ToString("yyyyMMddhhmmss");
return new HtmlString(builder.ToString());
}
Then in your views (not sure if you're using MVC, but the solution is similar in either case), you can use:
@Html.Script("/Scripts/common.js")
Which will output:
<script src="/Scripts/common.js?modified=20120129025804"></script>
Note: Page Speed is not happy with the use of the query string. However, I tried changing it to using a "/" and that resulted in MVC taking over the routing for the file, and preventing IIS from handling it. Not sure how to resolve that.
Instead of making the version as part of the file name, you can put it as a query string at the end, i.e.:
<script src="mysite/scripts/defualt.js?v=123" > </script>
I believe most modern browsers respect this, but I don't know if it would be 100% effective on all browsers.
Also, as a quick aside, I realize your example is probably that, just an example, but you shouldn't use a self-closing external script tag, it causes issues with most browsers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With