Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

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 }
        }
    });
});

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?

For reference, here is where the jQuery is loaded:

        @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:

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

And the 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
651 views
Welcome To Ask or Share your Answers For Others

1 Answer

Create a new section MyScripts below all other library scripts

_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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...