Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery After Body ASP .NET MVC 4

I just created an ASP .NET MVC 4 WebAPI project.

In looking at the default _Layout.cshtml, I see that the jquery script is being inserted after the body is rendered (not in the head).

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
    @Styles.Render("~/Content/themes/base/css", "~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
</head>
<body>
    @RenderBody()

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

This causes the error

$ is not defined 

of course, trying to write

$(document).ready(function() {...}).

Moving the

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

into the head section of the _Layout.cshtml corrects the problem and jquery works as expected.

What's up? Am I doing something wrong and there's a reason for the default location of the Script.Render inside _Layout.cshtml?

like image 259
Jeff Avatar asked Aug 12 '12 22:08

Jeff


2 Answers

Script loading and executing block the rendering of the page.

You can see this by adding alerts in multiple parts of your page. That's why it's recommended to put the js files at the back of the page.

You can also remedy your problem by having a section for page scripts behind the one where jquery is added, at the end of the page.

Edit: Here's an article from Scott Guthrie about sections in razor: http://weblogs.asp.net/scottgu/archive/2010/12/30/asp-net-mvc-3-layouts-and-sections-with-razor.aspx

like image 176
linkerro Avatar answered Oct 30 '22 16:10

linkerro


@Scripts.Render("~/bundles/jquery") is causing a problem with MVC 4 and VS 2010. This problem becomes more apparent when you try to create jQuery dialog.

The only way out is, as JeffN825 stated, to comment out the @Scripts.Render("~/bundles/jquery").

Now the unknown known is: what is the ramification of commenting out @Scripts.Render("~/bundles/jquery")?

I am using the following jquery libraries:

<script src="../../Scripts/jquery-1.7.2.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-ui-1.8.23.min.js" type="text/javascript"></script>

Note: jquery-1.7.2.min.js would not function.

like image 25
Max Avatar answered Oct 30 '22 15:10

Max