Why Asp.Net MVC 5 put @Scripts.Render(“~/bundles/jquery”) at the bottom in _Layout.cshtml?

I put <script> blocks which use jQuery in the body of one (and only one) cshtml file which uses the template and they causes error because jQuery is not loaded yet.

What’s the point to put the @Scripts.Render("~/bundles/jquery") at the bottom of _Layout.cshtml file?

The bottom of the _Layout.cshtml.

    @RenderBody()
    <hr />
    <footer>
    </footer>
</div>

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

The following shows the generated source of the cshtml file.

<script>
    $(document).ready(function () { /// $ not defined.
        // .....
    });
</script>

    <hr />
    <footer>
    </footer>
</div>

<script src="/Scripts/jquery-1.10.2.js"></script>
<script src="/Scripts/bootstrap.js"></script>

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You can use sections :

in your layout :

...
<script src="/Scripts/jquery-1.10.2.js"></script>
<script src="/Scripts/bootstrap.js"></script>
@RenderSection("scripts", required: false)
...

in yours cshtml :

@section scripts {
    <script>
        $(document).ready(function () { /// $ not defined.
            // .....
        });
    </script>
}

Method 2

Just enclose it inside section scripts in .cshtml Page as shown.

@section scripts{
  <script>
  $(document).ready(function () { 
    // .....
  });
  </script>
}

Method 3

It’s a best practice to load your javascript files after every possible HTML element.

Knowing this, I would place your document ready handler after loading all libs.

 <hr />
    <footer>
    </footer>
</div>

<script src="/Scripts/jquery-1.10.2.js"></script>
<script src="/Scripts/bootstrap.js"></script>
<script>
    $(document).ready(function () { /// $ not defined.
        // .....
    });
</script>

Method 4

If the script is at the top of the page, and there are problems then it may cause the page to stop/take a long time loading. Putting them at the bottom allows the page the render fully before your scripting goes to work.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x