Sameul.T
Sameul.T

Reputation: 309

JQuery.js tag placement best practice MVC .net

Where should I put my <script src="~/lib/jquery/dist/jquery.js"></script> in _Layout.cshtml page? at the bottom or top section? now I have done my search, placing jquery.js at the bottom of the layout page will give page load performance. however, I come across a problem/error when @RenderBody(), the body requires to use jQuery before the script is been load and this caused $ not defined.

link - Layout in ASP.NET Core

My page looks exactly like the above link. any tips and tricks for work around the problem would be appreciated.

Upvotes: 0

Views: 85

Answers (1)

Alireza Ahmadi
Alireza Ahmadi

Reputation: 9953

You can solve the problem by having a section for page scripts behind the one where jQuery is added, at the end of the page.

So create a new section (say MyScripts) below all other library scripts in Layout:

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

And in view:

@section MyScripts {
    <script type="text/javascript">
        write your jquery script...
    </script>
}

I highly recommended reading this article about sections in Razor: https://weblogs.asp.net/scottgu/asp-net-mvc-3-layouts-and-sections-with-razor

Upvotes: 2

Related Questions