【问题标题】:Jquery scripts order in ASPNET MVC 4 applicationASPNET MVC 4 应用程序中的 Jquery 脚本顺序
【发布时间】:2012-11-15 03:58:42
【问题描述】:

我正在使用 jqgrid 开发一个 ASPNET MVC 4 项目。

那里,ASPNET MVC 4 默认放置

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

在_Layout.cshtml文件的最后。

现在,我有一个 Index.cshtml,它使用 jqgrid 之类的

<script type="text/javascript">
    jQuery("#ajaxGrid").jqGrid({

所以我必须包含类似的 jqgrid 脚本

@section jqgridScripts
{
    <script src="@Url.Content("~/Scripts/jqgrid/i18n/grid.locale-en.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jqgrid/js/jquery.jqGrid.min.js")" type="text/javascript"></script>
}

但是在使用 .jqgrid 之前,我需要加载 jqgrid 脚本,而这又需要加载 jquery 脚本,因此,jquery 脚本需要位于 _Layout.cshtml 文件的顶部而不是末尾。

根据最佳实践,jquery 脚本需要在文件末尾加载,但如果我这样做,在 Index.cshtml 文件中它不知道 jQuery 是什么。

我不能把 jqquery 脚本和下面的 jqgrid 脚本放在 _Layout.cshtml 文件的底部,因为上面是使用 jqgrid 脚本的 Index.cshtml 文件内容。

为了能够将 jQuery 放在最后并且仍然能够在视图中使用带有 jquery 的东西,我是否缺少一些东西?

谢谢!吉列尔莫。

【问题讨论】:

    标签: javascript jquery asp.net-mvc jqgrid asp.net-mvc-4


    【解决方案1】:

    __Layout.cshtml:

    @Scripts.Render("~/bundles/jquery")
    @RenderSection("jqgridScripts", required: false);
    
    @* for script in current page *@
    @RenderSection("pageScripts", required: false);
    

    索引.cshtml:

    @section pageScripts
    {
    <script type="text/javascript">
        jQuery("#ajaxGrid").jqGrid({
        ... 
    </script>
    }
    

    但最佳做法是为您的代码创建一个单独的 javascript 文件,如下所示:

    __Layout.cshtml:

    @Scripts.Render("~/bundles/jquery")
    @RenderSection("pageScripts", required: false);
    

    索引.cshtml:

    @section pageScripts
    {
        <script src="@Url.Content("~/Scripts/jqgrid/i18n/grid.locale-en.js")" type="text/javascript"></script>
        <script src="@Url.Content("~/Scripts/jqgrid/js/jquery.jqGrid.min.js")" type="text/javascript"></script>
        <script src="@Url.Content("~/Scripts/Site/myscript.js")" type="text/javascript"></script>
    }
    

    myscript.js:

    $(function() {
    
       jQuery("#ajaxGrid").jqGrid({ ... });
    
    });
    

    【讨论】:

      【解决方案2】:

      我也遇到过这个问题。不捆绑 jQuery 本身似乎有点违反直觉,但这是必须要做的。在标题中向上抛出一个 jQuery 脚本引用。如果您将 jQuery 脚本 src 属性设置为缩小的 google 托管实例的属性,那么脚本很可能已经缓存在您的客户端中。

      Here is a nice reference...

      【讨论】:

        猜你喜欢
        • 2013-05-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-04-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多