您需要做的是转到 Static>App_Start>BundleConfig.cs :
然后为您拥有的每个视图创建一个包:
public class BundleConfig
{
// For more information on Bundling, visit http://go.microsoft.com/fwlink/?LinkId=254725
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/GlobalScripts")
.Include("~/Static/Scripts/jquery-1.10.2.js"
, "~/Static/Scripts/json2.js"
, "~/Static/Scripts/jquery-ui-1.10.4.js"
//, "~/Static/Scripts/jquery.layout-1.3.0.js"
//, "~/Static/Scripts/jquery.layout.state.js"
, "~/Static/Scripts/helper.mainlayout.js"));
}
}
只需在 .Include() 中为视图中的每个 javascript 添加脚本路径,并为您拥有的每个视图继续添加 bundles.add(new ScriptBundle(<bundle path>))。
您将使用 CSS 包执行类似的步骤,但您将使用 StyleBundle 而不是 StyleBundle
为了减少代码的重复,尝试为每个相互依赖的 javascript 创建一个字符串列表,并对它们进行联合:
List<string> jqGridScripts = new List<string>
{"~/Static/Scripts/jquery.jqGrid.src.js"
, "~/Static/Scripts/i18n/grid.locale-en.js"
, "~/Static/Scripts/helper.jqgrid.js"};
List<string> jqStopwatch = new List<string>
{ "~/Static/Scripts/jquery.stopwatch.js" };
bundles.Add(new ScriptBundle("~/bundles/viewName")
.Include(jqGridScripts
.Union(jqStopwatch).ToArray()));
请记住,它们出现在数组中的顺序与它们出现在 HTML 中或被捆绑和缩小的顺序相同。
查看代码:
@section scripts{
@Scripts.Render("~/bundles/viewName");
}
HTML 中的结果代码
<script src="/WDCSS/bundles/viewName?v=T3IlBuvfGTiz62pwDuiPogFX1jQoxVC2tmp3K6wffBQ1"></script>
我的意见
我真的不知道我们是否应该这样做。对我来说,我将所有页面中使用的脚本分开放在一个单独的包中,以便将其缓存。然后为视图中使用的脚本创建另一个包。我想说的是,我们应该在捆绑、缩小和缓存之间取得平衡。