适当的位置加载jQuery的MVC中的布局视图 [英] Proper place to load jQuery in MVC Layout view

查看:197
本文介绍了适当的位置加载jQuery的MVC中的布局视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是默认模板,创建一个MVC 4,其中 @ Script.Render(〜包/ jQuery的)被称为@RenderBody()。按照帖子,这是推荐执行,以prevent脚本的加载阻止的页面的呈现

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

我想在我看来,增加一个小的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:

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

然而,这将总是抛出错误错误:'$'未定义因为jQuery没有加载之后才 RenderBody()

However, this will always throw the error Error: '$' is undefined because jQuery isn't loaded until after the 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?

有关参考,这里是jQuery的加载:

For reference, here is where the jQuery is loaded:

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

修改

我结束了移动上面的脚本到我scripts.js中的文件,并在布局页面加载它下面的jQuery,像这样:

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

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

和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?

推荐答案

以下的其他库脚本创建一个新的部分MyScripts

Create a new section MyScripts below all other library scripts

_layout

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

MyView的

MyView

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

现在的jQuery后,只得到一次加载自定义页面的脚本被加载。

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

这篇关于适当的位置加载jQuery的MVC中的布局视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆