18

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?

Jeff
  • 35,755
  • 15
  • 108
  • 220

3 Answers3

12

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

linkerro
  • 5,318
  • 3
  • 25
  • 29
3

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

Chris
  • 26,544
  • 5
  • 58
  • 71
Max
  • 31
  • 1
0

Although the accepted answer links to details about how to so this, a more direct answer would be as follows:

_Layout.cshtml contains the line...

@RenderSection("scripts", required: false)

...which will insert a section named "scripts" found in the view - e.g. Index.cshtml:

<p>This is Index.cshtml</p>
@section scripts {
   <script>
      $(document).ready(function() {
         alert("This script is inserted by RenderSection after jQuery script is inserted.")
      })
   </script>
}
andrew
  • 1,723
  • 2
  • 12
  • 24