1

In MVC4, Views have script elements included at the bottom of the page.

Eg. In _layout.cshtml (under Shared folder), <script> tags are placed at the very bottom. While I understand that this makes the page load faster, the problem is actually this:

In my Views, sometimes I happen to use some scripts like autocomplete, something like below:

<script type="text\javascript"> ...... </script>

which is not functional because scripts tag are included at the very end of the page. (JQuery is not even loaded at that time)

Painfully, I had to move the Script Bundle rendering to the top of the page. Like,

render jquery first
then load scripts

so, am I missing something or I should always keep my scripts tag at the top of the _layout.cshtml page ?

Thanks for your responses.

3 Answers3

4

Ok. The key is:

put your scripts anywhere in your page but enclose them within a @section Scripts.

This will ensure that wherever you place your scripts, the _layout.cshtml' renders them with theJQuery` included.

Because, in your _layout.cshtml you have this:

@Scripts.Render("~/bundles/RequiredBundles")
        @RenderSection("scripts", required: false) 
  • 1
    +1 for providing the proper MVC solution to this issue, but could be improved by showing a "@section scripts" example. – raider33 Jan 19 '14 at 23:29
0

You may want to put some scripts in $.ready which will only run when the whole page is loaded.

xing
  • 447
  • 2
  • 6
0

I think the reason the code generation does this is so if you add your own scripts into the bundles then they are executed after most of the html body is loaded into the dom.

If you make sure you use $.ready when coding your custom javascript then you should have no problem whether they are at the bottom of the page or in the head tag.

For personal preference I put them at the top (I like only having to look in the head tag to find which scripts are loaded) and make sure to use $.ready.

chris stevens
  • 316
  • 4
  • 14