简体   繁体   中英

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.

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 the JQuery` included.

Because, in your _layout.cshtml you have this:

@Scripts.Render("~/bundles/RequiredBundles")
        @RenderSection("scripts", required: false) 

您可能希望在$ .ready中放置一些脚本,这些脚本仅在加载整个页面时运行。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM