[英]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?
每当我为任何Web应用程序发布新版本的CSS或javascript文件时,我都会在HTML开头的URL中手动添加?v=#
(#是版本号,例如3或10),确保用户浏览器缓存不会妨碍更改。
但是某些应用程序的头部具有多个CSS和多个JS文件,并且要跟踪所有已更改的文件很繁琐。
我们在IIS服务器上使用ASP.NET平台,因此使用答案是强制浏览器重新加载缓存的CSS / JS文件的一种优雅方法是什么? 是不可能的,但我正在寻找类似的东西。 最好所有的JavaScript。
我喜欢该帖子中使用md5哈希的建议,但似乎无法找到一种计算CSS或JS文件的校验和的方法。
代码看起来像这样(使用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?
}
或者也许在Visual Studio中使用了postbuild流程,但是我从未做过,所以我不愿意尝试。
编辑
按照添加缓存配置文件在web.config中尝试此操作
<configuration>
<system.webServer>
<caching enabled="true">
<profiles>
<add extension=".js" policy="CacheUntilChange" />
<add extension=".css" policy="CacheUntilChange" />
</profiles>
</caching>
</system.webServer>
</configuration>
您的解决方案似乎要求浏览器两次提取文件,并且不能保证第一次提取的状态。 因此它不起作用。
缓存由服务器控制。 无法决定何时在客户端上提供新版本-除非您忽略缓存并始终获取新副本。
有很多方法可以实现缓存策略。 具有版本号的指纹就是其中之一。
我更喜欢使用ETag 。 让ETag成为filemtime,您就很好了。
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;
}
}
在用户界面页面中: script src="JSVersionUpdate("~/Scripts/Application/Abc.js")"
O / p: ~/Scripts/Application/Abc.js/version=1.0
浏览器仅在版本不同的情况下才从服务器请求JS文件,否则它将被缓存出去。现在我不需要告诉别人在部署后一次又一次清除缓存。我要做的只是在Web Config中更改版本号
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.