简体   繁体   English

mvc 4底部的脚本 - 不执行 <scripts> 在视图页面中

[英]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. MVC4 ,Views在页面底部包含script元素。

Eg. 例如。 In _layout.cshtml (under Shared folder), <script> tags are placed at the very bottom. _layout.cshtml (在“ Shared文件夹”下)中, <script>标记位于最底部。 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: 在我的Views ,有时我碰巧使用一些脚本,如autocomplete ,如下所示:

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

which is not functional because scripts tag are included at the very end of the page. 这是不起作用的,因为scripts标记包含在页面的最末端。 (JQuery is not even loaded at that time) (当时甚至没有加载JQuery)

Painfully, I had to move the Script Bundle rendering to the top of the page. 痛苦的是,我不得不将Script Bundle rendering移到页面顶部。 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 ? 所以,我错过了什么,或者我应该始终将我的scripts标记保存在_layout.cshtml页面的顶部?

Thanks for your responses. 谢谢你的回复。

Ok. 好。 The key is: 关键是:

put your scripts anywhere in your page but enclose them within a @section Scripts . 将您的脚本anywhere页面中的anywhere ,但将它们包含在@section Scripts

This will ensure that wherever you place your scripts, the _layout.cshtml' renders them with the JQuery` included. 这将确保无论您将脚本放置在何处, _layout.cshtml' renders them with the都会使用包含的_layout.cshtml' renders them with the

Because, in your _layout.cshtml you have this: 因为,在你的_layout.cshtml你有这个:

@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. 我认为代码生成这样做的原因是,如果你将自己的脚本添加到包中,那么它们会在大部分html主体加载到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. 如果你确保在编写自定义javascript时使用$ .ready,那么你应该没有问题,无论它们是在页面底部还是在head标签中。

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. 为了个人喜好,我把它们放在顶部(我只想查看head标签以找到加载的脚本)并确保使用$ .ready。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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