自动给CSS,JavaScript文件添加版本号

为静态文件添加Expires头是提高网站性能的重要法则。在iis中设置也很简单:

1.打开iis7管理界面,双击HTTP响应标头

  image

2.点击“设置常用表头”,打开对话框

image

 

 

但是这样带来的问题是如果我们要更改网站的静态文件,那么用户浏览器如果缓存了这些文件,浏览器不会检查任何更新,直到过了过期日期,为了让用户浏览器长时间缓存静态文件同时又“知道”我们什么时候更新了文件,唯一的方法就是改变文件的名称,如果手动修改的话完全是体力活。

在这里我使用一个简单的方法自动为文件添加版本号

1.首先使用ISAPI_Rewrite的重写功能,添加一条重写规则:

RewriteRule ^/(CSS|JavaScript)/(.*?)\.[0-9]+\.(css|js) /$1/$2\.$3 [L]

意思是如果我们访问的css文件的路径是:/CSS/test.100115221449.css 映射到得路径是:“/CSS/test.css”

2.接下来需要写一段简单的代码为文件设置版本号,这个版本号其实就是最后修改的日期

    private static string SetVersion(string filePath)
{
string verFilePath = filePath;
string serverPath = HttpContext.Current.Server.MapPath(filePath);
if (File.Exists(serverPath))
{
verFilePath = filePath.Insert(filePath.LastIndexOf(
'.'),
string.Concat(".", File.GetLastWriteTime(serverPath).ToString("yyMMddHHmmss")));
}
return verFilePath;
}

public static string CssLink(params string[] filePath)
{
var sb = new StringBuilder();
Array.ForEach(filePath, f => sb.AppendLine(string.Format(@"<link rel=""stylesheet"" type=""text/css"" href=""{0}"" />",
SetVersion(f))));
return sb.ToString();
}
public static string JavaScriptLink(params string[] filePath)
{
var sb = new StringBuilder();
Array.ForEach(filePath, f => sb.AppendLine(string.Format(@"<script type=""text/javascript"" src=""{0}""></script>",
SetVersion(f))));
return sb.ToString();
}

 

3.页面使用起来也很简单

<%=AutoVersion.CssLink("/CSS/test.min.css")%>

 

4.最后看看生成的页面吧

image

posted @ 2010-01-16 20:42  MicroCoder  阅读(4349)  评论(5编辑  收藏  举报