在 MVC 布局视图中加载 jQuery 的正确位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15347628/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 14:52:44  来源:igfitidea点击:

Proper place to load jQuery in MVC Layout view

jqueryasp.net-mvc

提问by Tom

I've created an MVC 4 using the default template, where @Script.Render(~"bundles/jquery")is called after @RenderBody(). As per thispost, this is the recommended execution order to prevent the loading of scripts to block the rendering of the page.

我使用的是默认模板,在那里创建了一个MVC 4@Script.Render(~"bundles/jquery")后调用@RenderBody()。根据这篇文章,这是推荐的执行顺序,以防止加载脚本以阻止页面呈现。

I want to add a small jQuery call in my view, or my RenderBody()section. It looks like this, at the top of my view:

我想在我的视图或我的RenderBody()部分中添加一个小的 jQuery 调用。在我看来,它看起来像这样:

<script type="text/javascript">
$(document).ready(function()
{
    $("#eta_table").tablesorter({
        headers: {
            0: { sorter: false }
        }
    });
});

However, this will always throw the error Error: '$' is undefinedbecause jQuery isn't loaded until after the RenderBody().

但是,这将始终引发错误,Error: '$' is undefined因为 jQuery 直到RenderBody().

I can't imagine this is a new problem, it seems like a fairly common task... Any suggestions on how this should be handled?

我无法想象这是一个新问题,这似乎是一个相当普遍的任务......关于如何处理这个问题的任何建议?

For reference, here is where the jQuery is loaded:

作为参考,这里是 jQuery 的加载位置:

        @Scripts.Render("~/bundles/jquery")
    @RenderSection("scripts", required: false)
</body>

Edit

编辑

I ended up moving the script above into my scripts.js file, and loaded it in below jQuery in the layout page, like so:

我最终将上面的脚本移动到我的 scripts.js 文件中,并将其加载到布局页面中的 jQuery 下方,如下所示:

            bundles.Add(new ScriptBundle("~/bundles/custom").Include(
                    "~/Scripts/Custom/tablesorter.js",
                    "~/Scripts/Custom/scripts.js"));

And the HTML:

和 HTML:

        @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/custom")
    @RenderSection("scripts", required: false)
</body>

Except this still seems wrong, as now the scripts are going to have to load for every page that uses the master layout view. It's working, but, is this the best way?

除了这似乎仍然是错误的,因为现在必须为每个使用主布局视图的页面加载脚本。它正在工作,但是,这是最好的方法吗?

回答by Jasen

Create a new section MyScripts below all other library scripts

在所有其他库脚本下方创建一个新部分 MyScripts

_Layout

_布局

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

MyView

我的看法

@section MyScripts {
    <script type="text/javascript">
        $("#eta_table");
        ...
    </script>
}

Now your custom page scripts only get loaded once after jQuery is loaded.

现在,您的自定义页面脚本只会在 jQuery 加载后加载一次。