我是 MVC 的新手,我注意到在加载我编写并尝试加载的 js 文件时存在很多不一致之处。
首先,这是我的网站设置方式:
_Layout.cshtml (main page)
Index.cshtml
_MainMenu.cshtml (partial view)
我在 Layout 主体中呈现我的 MainMenu。所有 jquery 脚本都加载在布局的页脚中(我在某个地方读到的比较好)。
当我呈现 View 时,我会在 View 顶部加载与该内容相关的任何特定脚本。
加载 javascript 文件的最佳方式是什么(无论是来自 google 的 cdn 文件还是我的项目中包含的文件)?我应该将它们全部加载到我的布局页面的标题中,还是只在我使用它们时加载它们?有人可以解释最佳实践以及在 mvc 应用程序中管理/加载/使用 javascript 文件吗。
感谢您的参与!
最佳答案
如果您使用 Modernizr ,将其加载到头部。在 body
的底部加载您的其他脚本,包括 jquery(除非另有说明——一些脚本需要是 head
)。理想情况下,您的 _Layout.cshtml 应如下所示:
<!DOCTYPE html>
<html lang="en">
<head>
<!-- head stuff -->
@Scripts.Render("~/bundles/modernizr")
</head>
<body>
<!-- your entire body -->
@Scripts.Render("~/bundles/jquery")
@RenderSection("scripts", required: false)
</body>
</html>
这将加载您的 jQuery 包,然后是您可以根据需要在每个页面加载自定义脚本的部分,例如(在其他一些 .cshtml
文件中):
@section Scripts {
@Scripts.Render("~/bundles/myNiceBundle")
}
因此它将把您的自定义脚本放在 jQuery 下。
Obligatory reason for putting scripts at bottom of page :
The problem caused by scripts is that they block parallel downloads. The HTTP/1.1 specification suggests that browsers download no more than two components in parallel per hostname. If you serve your images from multiple hostnames, you can get more than two downloads to occur in parallel. While a script is downloading, however, the browser won't start any other downloads, even on different hostnames.
关于javascript - MVC 4 - 在哪里加载 JS 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14784616/