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

巧了我就是萌 提交于 2019-12-11 14:24:21

问题


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.


回答1:


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) 



回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/19269039/scripts-at-the-bottom-in-mvc-4-does-not-execute-scripts-in-view-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!