在MVC 4.0中绑定javascript文件

Bundling javascript files in MVC 4.0

本文关键字:绑定 javascript 文件 MVC      更新时间:2023-09-26

我正在尝试在web应用程序中捆绑javascript文件以提高性能。举个例子,我试图加载一个缩小版的jQuery,但当我运行web应用程序时,jQuery没有加载。

捆绑包配置:

  public class BundleConfig
    {
        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(new ScriptBundle("~/bundles/jquery").IncludeDirectory("~/Scripts/","jquery-1.8.2.min.js"));
//Also tried this:
//bundles.Add(new ScriptBundle("~/bundles/jquery").Include("~/Scripts/jquery-1.8.2.min.js"));
            bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.css"));
        }
    }

主页:

@using System.Configuration
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <meta name="apple-mobile-web-app-capable" content="yes">
    <title>@ViewBag.Title</title>
    @Styles.Render("~/Content/css")   
    <script type="text/javascript">
        var screenRefreshTime = '@ConfigurationManager.AppSettings["ScreenRefreshTime"].ToString()';
        screenRefreshTime = parseInt(screenRefreshTime);
    </script>
</head>
<body>
    @RenderBody()
    @Scripts.Render("~/bundles/jquery")
    @RenderSection("scripts", required: false)
</body>
</html>

当你为它创建捆绑包时,你不需要包含min。我假设你在同一个文件夹中有jquery.1.8.2.js和jquery.1.8.2.2min.js,文件名除了"min"字外都是相同的。例如:jquery1.8.2.js,jquery.1.8.2min.js。你可以尝试直接包含,而不是包含目录。像这个的代码

  public class BundleConfig
  {
    public static void RegisterBundles(BundleCollection bundles)
    {
        bundles.Add(new ScriptBundle("~/bundles/jquery").Include("jquery-1.8.2.js"));
    }
}

还需要提到的是,如果您需要在调试模式下检查绑定,则绑定仅在发布模式下有效。

BundleTable.EnableOptimizations = true;

称之为

 @Scripts.Render("~/bundles/jquery")

IncludeDirectory的第二个参数是搜索模式,请尝试*.js

public class BundleConfig
{
    public static void RegisterBundles(BundleCollection bundles)
    {
        bundles.Add(new ScriptBundle("~/bundles/jquery").IncludeDirectory("~/Scripts/", "*.js"));
        bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.css"));
    }
}

或者使用Include而不是IncludeDirectory:

public class BundleConfig
{
    public static void RegisterBundles(BundleCollection bundles)
    {
        bundles.Add(new ScriptBundle("~/bundles/jquery").Include("~/Scripts/jquery-1.8.2.min.js"));
        bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.css"));
    }
}