scripts at the bottom in mvc 4 - Does not execute <scripts> in View page

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.

Upvotes: 1

Views: 4070

Answers (3)

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) 

Upvotes: 4

chris stevens
chris stevens

Reputation: 326

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.

Upvotes: 0

xing
xing

Reputation: 447

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

Upvotes: 0

Related Questions