bundles.Add(new ScriptBundle("~/bundles/textview") .Include( "~/Scripts/printarea/jquery.PrintArea.js","~/Scripts/pagedown/Markdown.Converter.js","~/Scripts/pagedown/Markdown.Sanitizer.js","~/Scripts/pagedown/Markdown.Editor.js" ));
这会创建一个缓存到期日期提前一年的文件,这是当我看看源代码时在我的脚本HTML中出现的:
<script src="/bundles/textview?v=cNvP0r6Jo6hsl2Sdzhw-o3kAK7t2JdcNWiG0iIg7Lys1"></script>
那么为什么我在提琴手中仍然看到它去服务器来检查文件是否被修改?有没有一种方法可以修改bundle例程,以便它不添加?v =,而是简单地将GUID附加到文件名中,例如两者之间的连字符?
解决方法
为什么服务器检查?
浏览器使用新鲜启发式来确定它们是否应该使用服务器验证资源,或者只是从缓存中提取资源.
浏览器将提供缓存的文件,而不用服务器进行验证,除非有以下情况之一:
>没有满足新鲜启发式(即缓存中的文件不被认为是新鲜的).
>您已更改过期标题或其他缓存标题.
>您已设置浏览器禁用缓存..
>资源的URL更改或不同.
<?xml version="1.0" encoding="UTF-8"?> <configuration> <system.webServer> <staticContent> <clientCache cacheControlMode="UseExpires" httpExpires="Thu,01 Jan 2016 00:00:00 GMT" /> </staticContent> </system.webServer> </configuration>
这将Expires Header设置为一年.这将允许您直接从缓存提供文件,而不必在下一年与服务器进行检查.
对于bundle,在System.Web.Optimization.dll中显式设置了标题:
private static void SetHeaders(BundleResponse bundle,BundleContext context) { if (context.HttpContext.Response != null) { if (bundle.ContentType != null) { context.HttpContext.Response.ContentType = bundle.ContentType; } if (!context.EnableInstrumentation && context.HttpContext.Response.Cache != null) { HttpCachePolicyBase cache = context.HttpContext.Response.Cache; cache.SetCacheability(bundle.Cacheability); cache.SetOmitVaryStar(true); cache.SetExpires(DateTime.Now.AddYears(1)); cache.SetValidUntilExpires(true); cache.SetLastModified(DateTime.Now); cache.VaryByHeaders["User-Agent"] = true; } } }
所以你需要检查你没有违反任何规则强制浏览器检查与服务器!
引用:
> Bundling and Minification
> Using CDNs and Expires to Improve Web Site Performance.
更新
如果您的目标是让您的脚本始终如下:
<script src="/Scripts/printarea/jquery.PrintArea.js"></script> <script src="/Scripts/pagedown/Markdown.Converter.js"></script> <script src="/Scripts/pagedown/Markdown.Sanitizer.js"></script> <script src="/Scripts/pagedown/Markdown.Editor.js></script>
而不是:
<script src="/bundles/textview?v=cNvP0r6Jo6hsl2Sdzhw-o3kAK7t2JdcNWiG0iIg7Lys1"></script>
然后将以下内容添加到RegisterBundles方法中(禁用捆绑和分类):
BundleTable.EnableOptimizations = false;
Unless
EnableOptimizations
istrue
or the debug attribute in the
compilation Element in the Web.config file is set tofalse
,files
will not be bundled or minified. Additionally,the .min version of
files will not be used,the full debug versions will be selected.
EnableOptimizations
overrides the debug attribute in the compilation Element in the Web.config file