为什么 Asp.Net MVC 5 将 @Scripts.Render("~/bundles/jquery") 放在 _Layout.cshtml 的底部?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25458717/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why Asp.Net MVC 5 put @Scripts.Render("~/bundles/jquery") at the bottom in _Layout.cshtml?
提问by ca9163d9
I put <script>
blocks which use jQuery in the body of one (and only one) cshtml file which uses the template and they causes error because jQuery is not loaded yet.
我将<script>
使用 jQuery 的块放在一个(并且只有一个)使用模板的 cshtml 文件的主体中,它们会导致错误,因为尚未加载 jQuery。
What's the point to put the @Scripts.Render("~/bundles/jquery")
at the bottom of _Layout.cshtml file?
将 放在@Scripts.Render("~/bundles/jquery")
_Layout.cshtml 文件的底部有什么意义?
The bottom of the _Layout.cshtml
.
的底部_Layout.cshtml
。
@RenderBody()
<hr />
<footer>
</footer>
</div>
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)
</body>
</html>
The following shows the generated source of the cshtml file.
下面显示了生成的 cshtml 文件的源代码。
<script>
$(document).ready(function () { /// $ not defined.
// .....
});
</script>
<hr />
<footer>
</footer>
</div>
<script src="/Scripts/jquery-1.10.2.js"></script>
<script src="/Scripts/bootstrap.js"></script>
回答by Pascalz
You can use sections :
您可以使用部分:
in your layout :
在您的布局中:
...
<script src="/Scripts/jquery-1.10.2.js"></script>
<script src="/Scripts/bootstrap.js"></script>
@RenderSection("scripts", required: false)
...
in yours cshtml :
在你的 cshtml 中:
@section scripts {
<script>
$(document).ready(function () { /// $ not defined.
// .....
});
</script>
}
回答by Kartikeya Khosla
Just enclose it inside section scripts
in .cshtml Page as shown.
只需将其包含section scripts
在 .cshtml 页面中,如图所示。
@section scripts{
<script>
$(document).ready(function () {
// .....
});
</script>
}
回答by sergserg
It's a best practice to load your javascript files after every possible HTML element.
最佳做法是在每个可能的 HTML 元素之后加载您的 javascript 文件。
Knowing this, I would place your document ready handler after loading all libs.
知道了这一点,我会在加载所有库后放置您的文档就绪处理程序。
<hr />
<footer>
</footer>
</div>
<script src="/Scripts/jquery-1.10.2.js"></script>
<script src="/Scripts/bootstrap.js"></script>
<script>
$(document).ready(function () { /// $ not defined.
// .....
});
</script>
回答by TSK007
If the script is at the top of the page, and there are problems then it may cause the page to stop/take a long time loading. Putting them at the bottom allows the page the render fully before your scripting goes to work.
如果脚本位于页面顶部,并且出现问题,则可能会导致页面停止/加载时间过长。将它们放在底部可以让页面在脚本开始工作之前完全呈现。