繁体   English   中英

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

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

MVC4 ,Views在页面底部包含script元素。

例如。 _layout.cshtml (在“ Shared文件夹”下)中, <script>标记位于最底部。 虽然我知道这会使页面加载更快,但问题实际上是这样的:

在我的Views ,有时我碰巧使用一些脚本,如autocomplete ,如下所示:

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

这是不起作用的,因为scripts标记包含在页面的最末端。 (当时甚至没有加载JQuery)

痛苦的是,我不得不将Script Bundle rendering移到页面顶部。 喜欢,

render jquery first
then load scripts

所以,我错过了什么,或者我应该始终将我的scripts标记保存在_layout.cshtml页面的顶部?

谢谢你的回复。

好。 关键是:

将您的脚本anywhere页面中的anywhere ,但将它们包含在@section Scripts

这将确保无论您将脚本放置在何处, _layout.cshtml' renders them with the都会使用包含的_layout.cshtml' renders them with the

因为,在你的_layout.cshtml你有这个:

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

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

我认为代码生成这样做的原因是,如果你将自己的脚本添加到包中,那么它们会在大部分html主体加载到dom之后执行。

如果你确保在编写自定义javascript时使用$ .ready,那么你应该没有问题,无论它们是在页面底部还是在head标签中。

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

暂无
暂无

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

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