受到 Darin 解决方案的启发,我决定使用 Bundling and Minification 以获得它所提供的所有好处的好处,我想出了以下解决方案。为 Page 类型添加一个带有 Extension 方法的静态类:
public static class ScriptExtensions
{
public static string Script(this Page page, string relativeUrl)
{
var path = page.Server.MapPath(relativeUrl);
if (File.Exists(path))
{
return BundlesConfig.AddPageScript(relativeUrl);
}
return string.Empty;
}
}
类BundlesConfig
contians 方法为 js 文件生成 bundle 并添加到 Bundles:
public class BundlesConfig
{
private static readonly ICollection<string> addedScripts
= new HashSet<string>();
private static readonly string bundleTemplate = "~/bundles/scripts/{0}";
internal static string AddPageScript(string relativeUrl)
{
var fileName = CleanFileName(relativeUrl);
var bundleName = string.Format(bundleTemplate, fileName);
if(!addedScripts.Contains(fileName))
{
var bundle = new ScriptBundle(bundleName);
bundle.Include(relativeUrl);
addedScripts.Add(fileName);
BundleTable.Bundles.Add(bundle);
}
return System.Web.Optimization.Scripts.Render(bundleName).ToHtmlString();
}
private static string CleanFileName(string url)
{
if (url.Contains("/"))
{
return url.Substring(url.LastIndexOf("/") + 1).Replace('.', '_')
.Replace("-", "__");
}
return url.Replace('.', '_').Replace("-", "__");
}
}
现在在页面而不是标准script
标签上:
<scrip type="text/javascript" src="/scripts/jquery-min.js"></script>
我们用:
<%= this.Script("~/Scripts/jquery-min.js") %>
该方法吐出以下内容:
<script type="text/javascript" src="/bundles/scripts/jquery__min_js?v=...."></script>